[英].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>
对于此表,我动态添加了cells(“ 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()函数,结果我将重复项添加到第二张表中。 我找不到为什么这样做的模式。 你能建议我吗?
我的变更:
.one
更改为.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>");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.