由于我有动态添加的内容,我需要使用“文档”作为我的事件的选择器。
$(document).hover(function(){
//Do something
}
现在我想知道我是否也可以使用类作为选择器?
我尝试过:
$(document).hover('.liDoc', function(){
$(this).children('.delDoc').css('color', 'red'); console.log($(this).children('.delDoc'))
}, function() {
// on mouseout, reset the background colour
$(this).children('.delDoc').css('color', '');
});
这个不行!看起来整个文档都是目标。
当使用 .on()
时,我可以这样做......但是 .on('hover')
已被弃用?!
最佳答案
您需要委托(delegate) mouseenter/mouseleave
事件并按事件类型进行过滤,例如:
$(document).on('mouseenter mouseleave', '.liDoc', function(e) {
$(this).children('.delDoc').css('color', e.type === "mouseenter" ? 'red' : '');
});
但是你最好切换一个类:
$(document).on('mouseenter mouseleave', '.liDoc', function(e) {
$(this).children('.delDoc').toggleClass('colored');
});
在 CSS 中:
.delDoc.colored {
color: red;
}
或者如果您的用例与您发布的用例一样简单,则只需使用 CSS:
.liDoc:hover > .delDoc {
color: red;
}
关于javascript - 如何使用文档 AND 类作为 Jquery .hover() 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41059113/