簡體   English   中英

.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>

對於此表,我動態添加了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM