如何防止JavaScript上的双重绑定
How can I prevent double binding on JavaScript?
这是我的情况,我有一个可以动态添加/删除行的表,当页面加载时,我需要绑定删除行。
这是我的代码:
<script type="text/javascript">
$(document).ready(function(){
$(".btnRemoveRow").bind("click", removeRow); });
</script>
但当我在外部js 上添加行时,我还需要绑定另一个removeRow
function addRow(){
{--add row code here--}
$(".btnRemoveRow").bind("click", removeRow);
}
以便新添加的行也将与removeRow函数绑定
这是我的removeRow函数:
function removeRow(){
var row = $(this).closest('tr');
var selected = row.find('input.qty,input.price,textarea,select').val();
$.getScript("calculate.js", function(){});
if(selected)
{
var r=confirm("Confirm Remove?");
if (r==true)
{
row.find('input.qty,input.price,textarea,select').attr("disabled", true);
row.find('input.hidden-deleted-id').val("yes");
row.find('.subtotal>center>h3').text("0");
calculate();
row.hide();
return false;
}
else
{
return false;
}
}
else{
row.find('input.qty,input.price,textarea,select').attr("disabled", true);
row.find('input.hidden-deleted-id').val("yes");
row.find('.subtotal>center>h3').text("0");
calculate();
row.hide();
return false;
}
};
情况1:当我删除行而不首先添加任何行时,它工作正常(对话框只显示一次)。
情况2:当我先添加行,然后删除已经绑定在页面上的行时,对话框会出现两次。
情况3:当我删除我添加的行时,它运行良好(对话框出现一次)。
(附言:仍在学习JavaScript)
你知道我该怎么解决第二个案子吗?
添加一个委托的事件处理程序,这样它将适用于现有元素和未来的元素
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", ".btnRemoveRow", removeRow);
});
</script>
用最接近的非动态父元素替换CCD_ 1。
试试这个:
<script type="text/javascript">
$(function(){
$(".btnRemoveRow").click(function(){removeRow();});
});
</script>
相关文章:
- 如何在拖动绑定到“mousedowd,mousemove,mouseup”的锚点时防止重定向
- 如何防止 jQuery-UI 按钮集破坏 AngularJS 绑定
- 如何防止JavaScript上的双重绑定
- 防止拖动上的ko点击绑定
- 防止Angular范围变量通过引用自动绑定到服务私有成员
- jQuery:防止绑定的 js 在单击时运行,然后在满足条件时运行它
- 在后台发生什么,以防止调用更改此对象的绑定方法
- 将单选按钮绑定到复杂对象可防止选中
- 防止 KO 绑定处理程序在页面加载时触发
- 如何防止knockout.js数据绑定中的字符转义
- 防止文档绑定捕获keydown()
- 绑定mousedown的jQuery插件可以防止点击客户端代码
- 防止子iframe聚焦时文档丢失键绑定
- 如何防止用户修改绑定到html控件的javascript变量的值(使用任何web浏览器的调试器选项)
- 我想防止第二次点击,直到使用绑定和取消绑定完成动画,但它不起作用
- 如何防止vue.js覆盖组件中的jQuery绑定
- 如何防止AngularJS递归绑定?
- 如何防止AngularJS在窗体输入'无效时从模型中取消绑定
- 如何防止重新绑定对剑道网格数据项的更改
- 如何解除绑定或防止在函数运行时发生其他单击事件