jQuery - convert .live() to .on()

故事扮演 提交于 2019-12-17 20:36:19

问题


How do I go about combining this old jQuery code into the v1.7 .on()?

v1.3 .live():

    $('#results tbody tr').live({
    mouseenter:
       function () { $(this).find('.popup').show(); },
    mouseleave:
       function () { $(this).find('.popup').hide(); }
    });

v1.7 .on():

$('#results tbody').on('mouseenter', 'tr', function () {
    $(this).find('.popup').show();
});
$('#results tbody').on('mouseleave', 'tr', function () {
    $(this).find('.popup').hide();
});

I want to pass both event handlers to one .on() call, but keep the brilliant event delegation .on() allows me to do.

Thank you!


回答1:


You can pass an event-map as the first parameter:

$('#results tbody').on({
    'mouseenter' : function () {
        $(this).find('.popup').show();
     },
    'mouseleave' : function () {
        $(this).find('.popup').hide();
    }
}, 'tr');

jQuery documentation:

.on( events-map [, selector] [, data] ),
events-map A map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).




回答2:


I just want to pass both event handlers in one object, like I do in the first example.

In this case you could attach the two events together, then differentiate them in the handler itself, like this:

$('#results tbody').on('mouseenter mouseleave', 'tr', function (e) {
    if (e.type == "mouseenter") {
        $(this).find('.popup').show();
    }
    else {
        $(this).find('.popup').hide();
    }
});



回答3:


The formats used are specified in the documentation for live

$(document).on({...events...}, selector, data);

-or-

$(document).on(event, selector, data, callback);

The code for the live function in 1.7+ is now just a pass-through function:

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
}



回答4:


Taking your first example and changing live to on should be all that you need

 $('#results tbody tr').on({
mouseenter:
   function () { $(this).find('.popup').show(); },
mouseleave:
   function () { $(this).find('.popup').hide(); }
})

See: http://api.jquery.com/on/#example-6



来源:https://stackoverflow.com/questions/10636932/jquery-convert-live-to-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!