gpt4 book ai didi

输入文本框的 jQuery 悬停事件不起作用

转载 作者:行者123 更新时间:2023-12-01 06:21:57 27 4
gpt4 key购买 nike

我有一个包含 html 和 jQuery 代码的网页,如下所示。我已经订阅了 id 为 firstname 的输入文本框的悬停事件,但它永远不会在悬停在文本框上时触发。我已将此事件代码放置在文档就绪事件中。

此问题的演示位于以下 URL:demo sample

问题:下面用于订阅悬停事件的 jQuery 代码有什么问题?我的目标是每当文本框悬停在上方时应用 highlight 类。

HTML代码

<style>
.highlight {
background-color: yellow;
border: 1px red solid;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr class='class1'>
<td>
<!--some content here-->
I am a td element
</td>
<td>
<table>
<tr>
<td>
First Name
</td>
<td>
<input type='text' id='firstname'>
</td>
</tr>
<tr>
<td>
Last Name
</td>
<td>
<input type='text' id='lastname'>
</td>
</tr>
</table>
</td>
</tr>
</table>
<script>
$(document).ready(function() {
var firstName = $('#firstname');
firstName.on('hover', function() {
if($(this).hasClass('highlight') === false) {
$(this).addClass('highlight');
}
});
});
</script>

更新

根据答案,我更新了演示示例。您可以在以下 URL 中查看修改后的示例:modified demo sample that is working .

在这个修改后的示例中,我只是遵循了 DinoMyte 建议的方法,即在 jquery 中处理悬停效果/事件时使用以下格式: jQueryObject.hover(on function when hooverstarts, off function悬停时)

最佳答案

hover 事件可以绑定(bind),但不能委托(delegate)。您需要更换

firstName.on('hover', function() {

这样:

firstName.hover(function() {

工作中:https://jsfiddle.net/DinoMyte/jmt4bmtm/

如果您希望委托(delegate)该事件,则需要使用鼠标悬停的替代方法。

更新:如果您希望在悬停时触发开关效果,您可以执行以下操作:

 $(document).ready(function() {
var firstName = $('#firstname');
firstName.hover(function()
{
if($(this).hasClass('highlight') === false)
$(this).addClass('highlight');
},
function()
{
$(this).removeClass('highlight');
}
);
});

工作示例:https://jsfiddle.net/DinoMyte/jmt4bmtm/1/

如果委派对您的解决方案确实很重要,您可以使用以下使用鼠标事件的方法。

 $(document).ready(function() {
var firstName = $('#firstname');
firstName.on("mouseover",function()
{
if($(this).hasClass('highlight') === false)
$(this).addClass('highlight');
}).on("mouseleave",function()
{
$(this).removeClass('highlight');
});
});

工作示例:https://jsfiddle.net/DinoMyte/jmt4bmtm/3/

关于输入文本框的 jQuery 悬停事件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34346983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com