我有一个点击函数主体,可以有条件地添加或删除按钮。
添加有效,但 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()
当您想要丢弃该元素时使用。
关于javascript - jQuery detach() 和remove() 都不适用于附加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33157430/