我有两张桌子:
第一个表保存用户的答案,然后让用户从表中选择单元格。 第二个表反映了第一个表中选择的单元格。
第一张表:
<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()函数,结果我将重复项添加到第二个表中。我无法找到它为什么会这样做的模式。你能建议我吗?
答案 0 :(得分:3)
我的更改:
.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>");
});
});