无法理解jquery bind&的行为。与点击事件一起生活

时间:2013-07-18 07:36:17

标签: jquery

fiddle of the issue

$('div').not('#logs').each(function () {
    var id = $(this).attr('id');
    $("#" + id).bind('click', function () {
        $('#logs').append('\n' + $(this).attr('id') + '\n');
    });
});

$(".test").live('click', function () {
    alert('from x');
});

我会做的就是创建一些div并使用每个函数循环遍历所有div,并且会为每个div绑定一个click事件。

在类名'test'的每个div中都有跨度,我将绑定实时功能,如上所述。单击跨度时,只会显示“来自x”的警报,但我无法理解该行为。

行为就像是,绑定功能也在工作,实时功能也在工作。

请告诉我的句子错误,我在解释这个问题时有点低。 等待行为的解释。

由于

2 个答案:

答案 0 :(得分:0)

事件绑定到附加事件时页面上存在的元素。

在您的情况下,当发生这种情况时,元素始终出现在页面上。因此,绑定事件的方式都有效。

第二种情况是事件委托,它用于将事件绑定到动态创建的事件,即在事件绑定后附加到DOM的元素。因此,当您使用live绑定事件时,事件将附加到始终存在的文档中。其中使用了事件冒泡的概念

Ajax请求

之后,可能会将元素插入到dom中

<强>代码

您不需要$.each循环,因为选择器会选择与之匹配的所有元素

$('div').not('#logs').click( function () {
        $('#logs').append('\n' + this.id + '\n');
});

// live has be deprecated to delegate events as of jQuery 1.7
// use on instead to bind the events for event delegation
$(document).on('click', ".test", function () {
    alert('from x');
});

<强> Check Fiddle

答案 1 :(得分:0)

事件冒泡DOM树,触发任何处理程序绑定沿途的元素。

您通常会通过调用event.stopPropagation()来停止传播,但是由于.live()方法在事件传播到文档顶部后处理事件,因此您的父元素click()方法已经存在被叫了。

您可以通过将代码更改为以下内容,使代码按预期工作:

$(".test").on('click', function (event) {
    alert('from x');
    event.stopPropagation();
});

如果您确实需要使用.live(),例如,如果您要动态创建这些内容,那么请使用.bind()代替您的父元素,也可以使用.live(),例如:

$('div').not('#logs').each(function () {
    var id = $(this).attr('id');
    $("#" + id).live('click', function () {
        $('#logs').append('\n' + $(this).attr('id') + '\n');
    });
});

$(".test").live('click', function (event) {
    alert('from x');
    event.stopPropagation();
});

您还可以使用更受青睐的'.on()'方法,而不是折旧的.live(),如下所示:

$('div').not('#logs').each(function () {
    var id = $(this).attr('id');
    $(document).on('click', "#" + id, function () {
        $('#logs').append('\n' + $(this).attr('id') + '\n');
    });
});

$(document).on('click', ".test", function (event) {
    alert('from x');
    event.stopPropagation();
});
相关问题