如何使用活动切换事件?

如何使用活动切换事件?

问题描述:

我有以下代码

$(".reply").toggle
(
    function ()
    {
        x1();
    },
    function ()
    {
        x2();
    }
);

我需要使用 live ,所以新元素也将被束缚。有没有一些语法呢?或者,我需要在点击事件上实现切换

I need to use live, so new elements would also be bound. Is there some syntax to do it? Or will I need to implement a toggle on the click event?

我正在使用jQuery 1.4.2。

I am using jQuery 1.4.2.

只是修改了fehay的答案,以便它不依赖于jQuery在 toggle()中附加重复的事件处理程序toggle()

Just modified fehay's answer so that it does not rely on jQuery not attaching duplicate event handlers during toggle()

$(".reply").live('click', function () {
    var toggled = $(this).data('toggled');
    $(this).data('toggled', !toggled);
    if (!toggled) {
        x1();
    }
    else {
        x2();
    }
});

此外,请注意,的选择器直播由于事件代理的工作方式必须尽可能具体。每当有人点击文档时,jQuery都必须爬上树,检查元素是否与选择器匹配。同样的原因, .delegate()的性能要好得多因为您可以限制捕获区域。

Besides, just keep in mind that the selectors for live have to be as specific as possible because of the way event delegation works. Every time something gets clicked on the document, jQuery has to climb up the tree checking if the element matches the selector.For the same reason, .delegate() is much more performant because you can limit the capture area.