简体   繁体   中英

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

The below code is not binding the event to an appended element (using .insertBefore() ).

From my understanding, .on() is supposed to work like .live() . Is this not the case?

<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');
    });

To use it the way you want, you need to place the selector in the function and bind the event to the document:

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

And, like jfriend00 suggested, it's more efficient to bind the event to the closest parent:

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

It depends upon where you put the selector. Putting it in the first jQuery object does not have any .live() behavior. It binds static event handlers.

Specifying a comment parent object in the jQuery object and putting the selector in the arguments to .on() gives you live behavior:

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

It will work even more efficiently (and better than .live() ) if you pick a common parent that is closer to the actual objects than document.body. A problem with .live() was too many event handlers (all with selectors to check) on the document object. .on() works more like .delegate() and allows you to put the event handler on a common parent that is closer to the actual objects.

EDIT: Now that you've included your HTML, more efficient code would be this with a common parent selector in the jQuery object and the simplest possible selector in the .on() arguments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM