2016-09-22 85 views
1

我有一個td中的按鈕表,一旦我按下按鈕它將文本添加到td。我想在td裏面刪除這個文本,一旦我再次按下按鈕。注意這個按鈕在表中多次使用,因此是class屬性。 我可以使用哪種方法來完成這項工作?JQuery撤消追加

這是我的代碼:

$(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 
    }; 
}); 

回答

2

您可以爲文本創建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(); 
    }; 
}); 
+0

這似乎,工作,如果我只用一個按鈕,如果我想在每一個此添加此按鈕將無法正常工作?我會改進我的問題。 – Roy123

+1

然後您將需要唯一的ID,例如在像中插入TR號碼ID,然後按按鈕發送數據通過與TR號碼相同的按鈕ID – Imphusius

+0

http:// stackoverflow .com/a/546055/6501094這爲我工作 – Roy123

1

兩種方式:

1)追加的文字與一個跨度唯一的ID,然後刪除此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)[lame and wrong]將以前的.html() - 元素的整個HTML代碼 - 保存到全局變量中;然後在必要時從全局變量中恢復以前版本的文本。

2

請嘗試以下方法:

$(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(); 
    }; 
});