.one() jQuery函数会自动触发多次
.one() jQuery function is raised multiple times automatically
我有两个表:
第一个表保存用户的答案,然后让用户从表中选择单元格。第二个表反映了在第一个表中选择的单元格。
第一个表:
<table id="first_table">
<tr>
@foreach (var item in ViewBag.parameters) //for example ViewBag.parameters has 3 items
{
<th>@item</th>
}
</tr>
</table>
对于这个表,我动态地添加单元格("td")。每个单元格都有一个输入框,用于输入用户的答案。
第二个表:
<table id="second_table">
@foreach (var item in ViewBag.parameters)
{
<tr><th>@item :</th></tr>
}
</table>
然后我有一个按钮,从第一个表中选择单元格并将它们添加到第二个表中。此外,它刷新第二个表,并让用户再次从第一个表中选择单元格:
$("#clear_Button").click(function (e) {
alert("click from clear_button");
$("#second_table td").each(function (e) {
$(this).remove();
}); //remove all the cells from the second table
e.stopPropagation();
$("#first_table td").css("border", "1px solid black");
$("#first_table td").one('click', function (evt) {
alert("click from .one()");
$(this).css("border", "3px solid yellow"); //mark the clicked cell
var id_col = $(this).parent().children().index($(this)); //index for the second table where to append the cell
$("#second_table tr:eq(" + id_col + ")").append("<td>" + $(this).children().val() + "</td>");
});
});
有时,当我单击.one()函数一次时,它会被触发多次,结果我将重复的数据添加到第二个表中。我找不到它为什么会这样做的规律。你能推荐我吗?
我的改变:
- change
.one
to.bind
- 在一个函数中增加了
.unbind
来解除被点击单元格的事件监听器绑定 - 添加了
.unbind
在开始点击功能,以删除任何旧的事件监听器
JavaScript
$("#clear_Button").click(function (e) {
$("#first_table td").unbind(); //remove all existing event-listeners for all cells
$("#second_table td").each(function (e) {
$(this).remove(); //remove all the cells from the second table
});
e.stopPropagation();
$("#first_table td").css("border", "1px solid black");
$("#first_table td").bind('click', function (evt) {
$(this).unbind(); //remove the event-listener for the clicked cell
$(this).css("border", "3px solid yellow"); //mark the clicked cell
var id_col = $(this).parent().children().index($(this)); //index for the second table where to append the cell
$("#second_table tr:eq(" + id_col + ")").append("<td>" + $(this).children().val() + "</td>");
});
});
相关文章:
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 如何在JQuery函数中定义一个值,然后调用另一个函数并使用该值
- 如何从jquery函数返回变量
- 如何将具有文本类型值的var放入jQuery函数中
- Jquery函数在错误的时间提交
- 锚链接无法使用.slideUp jquery函数
- 重新分解jQuery函数
- 如何在视图模型contet更新更新上调用Jquery函数
- 如何向这个javascript/jquery函数添加参数
- 添加类来触发jquery函数
- 更改智能表中的页面将停止JQuery函数的工作
- 使用每500ms运行一次的jquery函数是个好主意吗
- jQuery函数不能只在一个页面上工作
- 如何将jquery函数链接到vanilla选择器
- 仅在小型设备上调用jQuery函数
- 如何将jquery函数仅应用于大屏幕
- 奇怪的jquery函数行为
- Backbone listenTo不将jquery函数作为处理程序进行激发
- 在jquery函数内部设置来自jquery函数的var;t运行
- 从Jquery函数中获取一个变量