由于我具有动态添加的内容,因此我需要使用“文档”作为事件的选择器。

$(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')

最佳答案

您需要委派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;
}

10-04 16:53