在 jQuery 元素停止工作之前只能单击一次
Can only click jQuery element once before it stops working
我有以下代码:
$("#another").click(function() {
$('#another').replaceWith('<a id="another" class="btn btn-primary btn-mini disabled"><i class="icon-refresh icon-white"></i> 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> 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> 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> 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> 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> 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> Loading...");
$.get("another.php", {
cycle: i
}, function(data) {
$("tbody").append(data);
a.html("<i class='icon-plus icon-white'></i> Load another cycle");
i++;
});
});
})();
这种方法的好处是DOM操作较少,没有内联JavaScript,也没有全局函数或变量。如果外部标记相同,则确实没有理由每次都销毁按钮并重新创建它。
相关文章:
- 单击一次后禁用按钮-第2部分
- 如何对每个用户每天只允许单击一次的按钮进行编码
- 为每个字母单击一次
- 对同一类中的所有元素单击一次
- 单击一次以静音,另一次单击可取消静音
- 如何加载一个html页面并在其中只需单击一次即可运行函数
- 只需单击一次按钮,jquery即可自动淡入/淡出文本
- 菜单在每单击一次时切换不同的动画
- 双击时设置内容可编辑 - IE 不允许编辑,除非再单击一次
- 允许按钮在流星中只单击一次
- PHP 在输入内单击一次
- 如何创建只能单击一次的点击处理程序
- 每次单击一次迭代两个数组并制作动画
- 限制用户仅单击一次标记
- Javascript:同时启用 2 个文本框,单击一次复选框
- 在 jQuery 元素停止工作之前只能单击一次
- 单击一次按钮即可用随机化值填充多个输入
- 画布仅每隔单击一次即可更新
- 使用Javascript/jQuery单击一次
- 单击一次即可启动多个闪烁按钮