提问者:小点点

在jQuery元素停止工作之前,只能单击它一次


我有以下代码:

$("#another").click(function() {
    $('#another').replaceWith('<a id="another" class="btn btn-primary btn-mini disabled"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>');
    $.get('another.php', { 'cycle' : i }, function(data) {
        $('tbody').append(data);
        $("#another").replaceWith('<a id="another" class="btn btn-primary btn-mini"><i class="icon-plus icon-white"></i>&nbsp;Load another cycle</a>');
    });
    i++;
});

当我单击具有另一个id的元素时,它会加载一次。点击一次之后,就再也不行了。


共2个答案

匿名用户

如果用另一个元素替换该元素,则所有侦听器都将被移除。为了避免这种情况,您可以将侦听器再次添加到新元素中

$('#another').bind('click', function() {
  //do something
});

或者将代码移动到函数中,并将onclick属性添加到元素中。

onclick="my_function();"

在您当前的javascript中

$('#another').replaceWith('<a id="another" class="btn btn-primary btn-mini disabled" onclick="my_function();"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>');

匿名用户

您将用一个没有事件侦听器的节点替换该节点。

基本上在点击之前

[#another]
    ^
    |
[clickListener]

然后生成另一个按钮( 加载...)

[#another]     [#another](2)
    ^
    |
[clickListener]

然后我们用布局中的第二个替换第一个:

[#another]               [#another](2)
    ^
    |
[clickListener]

哦,等等,我的模型什么都没变。这是因为click侦听器链接到了第一个对象(不再可见),而可见的对象仍然存在。

那么代码方面,这意味着什么呢?这仅仅意味着您需要将事件侦听器重新连接到那里。我会这样做的

var onClick=function(){
    $('#another').replaceWith('<a id="another" class="btn btn-primary btn-mini disabled"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>')
    .click(onClick); // <--- this is the important line!

    $.get('another.php', { 'cycle' : i }, function(data) {
        $('tbody').append(data);
        $("#another").replaceWith('<a id="another" class="btn btn-primary btn-mini"><i class="icon-plus icon-white"></i>&nbsp;Load another cycle</a>');
    });
    i++;
}

$("#another").click(onClick);