[英]jQuery detach() and remove() both not working on appended element
我有一個單擊功能,可以有條件地添加或刪除按鈕。
該添加有效,但是remove()
和detach()
不起作用。
我正在旋轉圖像,並且從原始圖像旋轉圖像時,我只想顯示一個“保存”按鈕。
這一切都已准備就緒
$(document).ready(function() {
var $save = $('<div id="savebutton_container"><button name="savebutton" id="savebutton">Save</button></div>');
$('body').on('click','img',function() {
if(typeof rotate.counter == 'undefined') {
rotate.counter = 0;
}
rotate.counter += 90;
if(rotate.counter === 360) {
rotate.counter = 0;
}
console.log(rotate.counter);
$(this).removeClass(function(index,css){ // clear classes first.
return (css.match (/(^|\s)rotate\S+/g) || []).join(' '); // remove rotational classes
});
if(!(rotate.counter == 0) ) { // NOT 0 degrees
console.log('rotate counter is not 0');
$(this).addClass('rotate' + rotate.counter); // rotate the image
if( $("#savebutton_container").length === 0 ) { // WORKS!
$(this).parents().append($save); // global $save
}
} else {
console.log('rotate counter is 0');
$("#savebutton_container").detach(); // works seemingly randomly
// Also tried $save.detach();// also tried .remove();
}
});
});
偶爾,保存按鈕將消失。 控制台始終應記錄“旋轉計數器為0”,但保存按鈕不會消失!
我認為問題出在您在一行中使用parents()
而不是parent()
$(this).parents().append($save);
parents()
方法返回該選擇中的所有祖先元素,並向上遍歷,而parent()
僅返回第一個父元素。
您正在檢索圖像的所有parents()
(例如<body>
, <html>
等),並將$save
附加到所有這些圖像。 在多元素選擇上使用append(elem)
導致elem
被克隆並附加到選擇中的每個目標。 這不是您想要的,這會導致您失去$save
引用(尤其是因為您要追加具有相同id
的元素的多個副本)。
該Plunkr具有您想要的略有簡化的工作版本(單擊圖像進行測試)。 請注意, detach()
是正確的, remove()
不是。 detach()
保留有關該元素的所有jQuery元數據,當您計划以后重新附加該元素時,將特別使用它。 當您想丟棄該元素時,使用remove()
。
我建議嘗試使用$(document).on('click'...)
代替$(body).on()
由於創建的元素是動態創建的,因此需要從dom樹的根開始重新檢查dom。
每當我使用動態元素時,我總是確保我的事件觸發器在$(document)
選擇器中運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.