简体   繁体   English

jQuery detach()和remove()都不适用于附加元素

[英]jQuery detach() and remove() both not working on appended element

I have a body on click function that conditionally adds or removes a button. 我有一个单击功能,可以有条件地添加或删除按钮。

The adding works, but neither remove() nor detach() works. 该添加有效,但是remove()detach()不起作用。

I am rotating an image and I only want to show a "Save" button when the image is rotated from the original. 我正在旋转图像,并且从原始图像旋转图像时,我只想显示一个“保存”按钮。

This is all inside document ready 这一切都已准备就绪

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

            }

    });
});

Every once in a while the save button will disappear. 偶尔,保存按钮将消失。 The console ALWAYS logs the "rotate counter is 0" whenever it is supposed to, but the save button does not go away! 控制台始终应记录“旋转计数器为0”,但保存按钮不会消失!

I think the problem comes from your usage of parents() instead of parent() in the line 我认为问题出在您在一行中使用parents()而不是parent()

$(this).parents().append($save);

The parents() method returns all ancestor elements from the selection, traversing up, while parent() returns only the first parent. parents()方法返回该选择中的所有祖先元素,并向上遍历,而parent()仅返回第一个父元素。

You are retrieving all parents() of the image (eg <body> , <html> , etc.) and appending $save to all of them. 您正在检索图像的所有parents() (例如<body><html>等),并将$save附加到所有这些图像。 Using append(elem) on a multi-element selection results elem being cloned and appended to every target in the selection. 在多元素选择上使用append(elem)导致elem被克隆并附加到选择中的每个目标。 This is not what you want, and this is causing you to lose the $save reference (especially since you are appending multiple copies of an element with the same id ). 这不是您想要的,这会导致您失去$save引用(尤其是因为您要追加具有相同id的元素的多个副本)。

This Plunkr has a slightly simplified working version of what you want (click on the image to test). Plunkr具有您想要的略有简化的工作版本(单击图像进行测试)。 Note that detach() is correct, remove() is not. 请注意, detach()是正确的, remove()不是。 detach() preserves all jQuery metadata about the element, it is specifically used when you plan to re-attach the element later. detach()保留有关该元素的所有jQuery元数据,当您计划以后重新附加该元素时,将特别使用它。 remove() is used when you want to discard the element. 当您想丢弃该元素时,使用remove()

I would suggest trying to use $(document).on('click'...) instead of $(body).on() 我建议尝试使用$(document).on('click'...)代替$(body).on()

Since the element that you have created is dynamically created you need to recheck the dom starting from the root of the dom tree. 由于创建的元素是动态创建的,因此需要从dom树的根开始重新检查dom。

Whenever I am using dynamic elements I always make sure that my event triggers are running off of my $(document) selector. 每当我使用动态元素时,我总是确保我的事件触发器在$(document)选择器中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM