6

如何将这个旧的 jQuery 代码合并到 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();
});

我想将两个事件处理程序都传递给一个.on()调用,但保持出色的事件委托.on()允许我这样做。

谢谢!

4

4 回答 4

10

您可以将事件映射作为第一个参数传递:

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

jQuery 文档

.on( events-map [, selector] [, data] ) ,
events-map一个映射,其中字符串键表示一个或多个空格分隔的事件类型和可选的命名空间,值表示要调用的处理函数事件)。

于 2012-05-17T13:51:32.597 回答
3

我只想在一个对象中传递两个事件处理程序,就像我在第一个示例中所做的那样。

在这种情况下,您可以将两个事件附加在一起,然后在处理程序本身中区分它们,如下所示:

$('#results tbody').on('mouseenter mouseleave', 'tr', function (e) {
    if (e.type == "mouseenter") {
        $(this).find('.popup').show();
    }
    else {
        $(this).find('.popup').hide();
    }
});
于 2012-05-17T13:51:15.040 回答
1

使用的格式在live文档中指定

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

-或者-

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

1.7+中的函数代码live现在只是一个传递函数:

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
}
于 2012-05-17T13:49:03.393 回答
0

以您的第一个示例并更改liveon应该是您所需要的

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

请参阅:http ://api.jquery.com/on/#example-6

于 2012-05-17T13:52:02.443 回答