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

Can only click jQuery element once before it stops working

本文关键字:单击 一次 元素 jQuery 停止工作      更新时间:2023-09-26

我有以下代码:

$("#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 的元素时,它会加载一次。单击一次后,它将不再起作用。

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

基本上在点击之前你有

[#another]
    ^
    |
[clickListener]

然后构建另一个按钮 ( <a id="another" class="btn btn-primary btn-mini disabled"><i class="icon-refresh icon-white"></i>&nbsp;Loading...</a>

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

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

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

哦,等等,我的模型中没有任何变化。这是因为点击侦听器链接到第一个对象(不再可见),而可见的对象仍然存在。


那么从代码上讲,这意味着什么?这只是意味着您需要将事件侦听器重新附加到那里。这是我的做法

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);
如果将该

元素替换为另一个元素,则将删除所有侦听器。为避免这种情况,您可以再次将侦听器添加到新元素中

$('#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>');

最好只保留相同的按钮,使用相同的事件处理程序。只需动态更改文本并递增i即可。试试这个:

// Execute in a closure to isolate all the local variables
// Optional, but I like doing this when counter variables are involved
(function() {
    var button = $("#another");
    var a = button.find("a");
    var i = 1;
    button.click(function() {
        // Replace the inner html, not the entire element
        a.html("<i class='icon-refresh icon-white'</i>&nbsp;Loading...");
        $.get("another.php", {
            cycle: i
        }, function(data) {
            $("tbody").append(data);
            a.html("<i class='icon-plus icon-white'></i>&nbsp;Load another cycle");            
            i++;
        });
    });
})();

这种方法的好处是DOM操作较少,没有内联JavaScript,也没有全局函数或变量。如果外部标记相同,则确实没有理由每次都销毁按钮并重新创建它。