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

时间:2012-04-10 01:30:36

标签: javascript html

我有以下代码:

$("#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为id的元素时,它会加载一次。点击一下后,它将无法再次运行。

3 个答案:

答案 0 :(得分:2)

您正在使用没有事件侦听器的节​​点替换节点。

基本上在你点击之前

[#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);

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

最好只保留相同的按钮,使用相同的事件处理程序。只需动态更改文本并增加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,没有全局函数或变量。如果外部标记是相同的,那么每次都没有理由破坏按钮并重新创建它。