【问题标题】:JQuery undo appendJQuery 撤消追加
【发布时间】:2017-01-31 00:36:16
【问题描述】:

我在 td 中有一个带有按钮的表格,一旦我按下按钮,它就会将文本添加到 td。再次按下按钮后,我想删除 td 中的此文本。请注意,此按钮在表格中多次使用,因此是类属性。 我可以使用哪种方法来完成这项工作?

这是我的代码:

$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
    var label = $(this).text();
    if (label == "Add") { // it is "Add" by default
        $(this).text("Cancel");
        $('.ReleaseTD').append("<br>" + "test"); // td class="ReleaseTD"
    }
    // the code above this works
    else {
        $(this).text("Add");
        $('.ReleaseTD').remove("<br>" + "test"); 
        // this obviously is wrong but this is where i would like the correct code
    };
});

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您可以像这样为里面的文本创建 ID:

    $(document).on('click', '.releasebutton', function () { // button class="releasebutton"
        var label = $(this).text();
        if (label == "Add") { // it is "Add" by default
            $(this).text("Cancel");
            $('.ReleaseTD').append("<span id='textID'><br>" + "test</span>");
        }
        else {
            $(this).text("Add");
            $('#textID').remove(); 
        };
    });
    

    【讨论】:

    • 如果我只使用一个按钮,这似乎可以工作,如果我想在每个 中添加这个按钮,这是行不通的吗?我会改进我的问题。
    • 你需要唯一的ID,例如像这样插入TR编号ID 然后按下按钮通过与TR编号相同的按钮发送数据身份证
    【解决方案2】:

    两种方式:

    1) 将您的文本附加到具有唯一 ID 的 span 中,然后删除此 ID。例如,删除编号最大的 ID。最愚蠢的方法是将最新的 ID 存储在全局变量中。

    var global_last_appended_id = 0;
    
    $(document).on('click', '.releasebutton', function () { // button class="releasebutton"
        global_last_appended_id ++;
        $('.ReleaseTD').append("<span id='appended-text-" + global_last_appended_id + "'><br>" + "test</span>");
      }
        // the code above this works
        else {
            $(this).text("Add");
            $('#appended-text-' + global_last_appended_id).remove(); 
            global_last_appended_id--; //go one step back so next time we remove the previous paragraph
        };
    });
    

    更新:在您编辑后,我添加了多次撤消的功能。基本上可以无限次撤消。

    2) [蹩脚和错误] 将之前的 .html() - 元素的整个 HTML 代码 - 保存到全局变量中;然后在必要时从全局变量中恢复以前版本的文本。

    【讨论】:

      【解决方案3】:

      请尝试以下方法:

      $(document).on('click', '.releasebutton', function () { // button class="releasebutton"
          var label = $(this).text();
          if (label == "Add") { // it is "Add" by default
              $(this).text("Cancel");
              $('.ReleaseTD').append("<span id='txt_name'><br>" + "test</span>");
          }
          // the code above this works
          else {
              $(this).text("Add");
              $('#txt_name').remove(); 
          };
      });
      

      【讨论】:

        猜你喜欢
        相关资源
        最近更新 更多
        热门标签