javascript - .one() jQuery 函数自动多次引发

标签 javascript jquery

我有两个表:

第一个表格保存用户的答案,然后让用户从表格中选择单元格。 第二个表反射(reflect)了在第一个表中选择的单元格。

第一个表:

<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() 函数时,它会多次引发,因此我会在第二个表中添加重复项。我找不到它为什么会这样做的模式。你能给我推荐一下吗?

最佳答案

我的改变:

  • .one 更改为 .bind
  • 在单函数中添加了.unbind,以解除单击单元格的事件监听器的绑定(bind)
  • 在点击函数的开头添加了.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>");
    });
});

关于javascript - .one() jQuery 函数自动多次引发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24110936/

相关文章:

javascript - jQuery的val(value)如何在下拉框中设置选中的值(水下)

javascript - 从wordpress视频URL字段中获取Javascript中的值(在JW Player脚本中)

javascript - Bootstrap 导航面板和日期选择器,带有对 C# Controller 的 javascript 调用

javascript - 你能阻止innerHTML删除HTML、HEAD、BODY元素吗?

javascript - 在 JAVASCRIPT 中将 div 高度设置为 window.innerHeight

javascript - 选择选项后无法显示隐藏的 div

javascript - 使用 JavaScript 的 SlideDown() 无法按预期工作

javascript - jquery prev() 返回 undef

javascript - 根据元素属性重新排序 DIV

javascript - 如何放大 jQuery?