所以我正在尝试使用 .hover() 方法,该方法仅在悬停元素时才执行某些操作,并且没有特定的类。如果我将类添加到 HTML 中有问题的元素,它就可以正常工作。但是假设我有一个单击事件,它使用 .addClass() 添加使用 jQuery 的类。 hover() 方法随后会忽略已添加的类。够啰嗦了。这是代码。
$('.foo:not(.bar)').hover(function() {
someCrap(); //when hovering a over .foo that doesn't also have the class .bar, do someCrap
}
$('.foo').click(function(){
$(this).addClass('bar'); //after the element .foo gets another class .bar, the hover event written earlier continues to work, WTF
})
有什么想法吗?
最佳答案
.hover()
仅向已创建的元素 添加事件。您需要使用 .on()
还可以为 future 的元素 创建事件。这意味着您还需要设置一个parent。 parent 最好尽可能靠近应该有鼠标事件的children,以节省性能。
$('#parent').on({
mouseenter : function() {
"use strict";
// Do something
},
mouseleave: function() {
"use strict";
// Do something
}
}, ".foo:not(.bar)");
关于javascript - 在同一元素上使用 .addClass() 后修改 .hover(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12100432/