内(& # 39;mouseenter& # 39; . .不检测附加元素(jQuery)

.on('mouseenter'... not detecting appended element (jQuery)

本文关键字:元素 jQuery mouseenter 检测      更新时间:2023-09-26

下面的代码没有将事件绑定到附加元素(使用.insertBefore())。

根据我的理解,.on()应该像.live()一样工作。事实并非如此吗?

<div class="todoColumn">
    <div class="projectHeader">
        <div class="title">Example</div>Subtitle
    </div>
    <div class="todo">
        <div class="checkbox"><span class="check pictos">3</span></div>
        <div class="text">another test</div>
        <div class="floatfix"></div>
    </div>
    <div class="todo">
        <div class="checkbox"><span class="check pictos">3</span></div>
        <div class="text">another test</div>
        <div class="floatfix"></div>
    </div>
</div>

    $('.todoColumn .todo .checkbox').on('mouseenter', function() {
        $(this).find('.check').css('visibility','visible');
    });

这取决于你把选择器放在哪里。将它放在第一个jQuery对象中不会有任何.live()行为。它绑定静态事件处理程序。

在jQuery对象中指定一个注释父对象,并将选择器放在.on()的参数中,您将获得实时行为:

$(document.body).on('mouseenter', '.todoColumn .todo .checkbox', function() {
    $(this).find('.check').css('visibility','visible');
});

如果您选择比document.body更接近实际对象的共同父对象,它将更有效地工作(并且比.live()更好)。.live()的一个问题是文档对象上有太多的事件处理程序(都有选择器要检查). .on()的工作方式更像.delegate(),并允许您将事件处理程序放在更接近实际对象的公共父对象上。

编辑:现在你已经包含了你的HTML,更有效的代码将是在jQuery对象中有一个共同的父选择器和.on()参数中最简单的选择器:
$('.todoColumn').on('mouseenter', '.checkbox', function() {
    $(this).find('.check').css('visibility','visible');
});

要按您想要的方式使用它,您需要将选择器放在函数中,并将事件绑定到文档:

$(document).on("mouseenter", ".column .todo .checkbox", function(){
    // do stuff
});

并且,就像jfriend00建议的那样,将事件绑定到最近的父节点更有效:

$(".column .todo").on("mouseenter", ".checkbox", function(){
    // do stuff
});