简体   繁体   English

如何使用jQuery detach()方法将元素切入和切出DOM?

[英]How to toggle elements in and out of DOM using jQuery detach() method?

I have a group of divs arranged in a grid. 我有一组排列在网格中的div。

在此输入图像描述

To style each div I'm selecting them with the nth-child() pseudo-class . 为了设置每个div的样式,我使用nth-child() 伪类选择它们。

div.tile:nth-child(4n-7) .text { background-color: yellow; }

A user can hide divs by clicking on a button (which fires a jQuery function that adds a display: none rule to the class attribute in the selected div). 用户可以通过单击按钮来隐藏div(它会触发一个jQuery函数,该函数将display: none规则添加到所选div中的class属性)。

jQuery jQuery的

$('.hide-divs').click(function () {
     $('.dolphin').toggleClass('hidden');
    })

CSS CSS

.hidden { display: none; }

Here's the problem: 这是问题所在:

Even though display: none removes the div from the screen, it doesn't remove the div from the DOM, so the nth-child selector still counts it when applying styles, which in turn messes up the visual design of the grid. 即使display: none从屏幕中删除了div,它也不会从DOM中删除div,因此第nth-child选择器在应用样式时仍然会计算它,这反过来会混淆网格的视觉设计。

在此输入图像描述

The above layout is broken because only the first column should be yellow. 上面的布局被破坏了,因为只有第一列应该是黄色的。

So my first thought was to use the jQuery remove() method , which takes elements (and its descendants) out of the DOM. 所以我的第一个想法是使用jQuery remove()方法 ,它将元素(及其后代)从DOM中取出。

Turns out, however, once remove() is applied you can't get those divs back. 然而,事实证明,一旦应用了remove() ,你就无法获得这些div。 They're gone. 他们走了。 So the toggle function breaks. 因此切换功能会中断。

After a bit of research I discovered the jQuery detach() method , which does the same thing as .remove() , except it stores the removed elements' data for later use. 经过一些研究后,我发现了jQuery detach()方法 ,该方法.remove()相同的操作,除了它存储已删除元素的数据供以后使用。

From the jQuery website : 来自jQuery网站

The .detach() method is the same as .remove() , except that .detach() keeps all jQuery data associated with the removed elements. .detach()方法与.remove()相同,除了.detach()保留与删除的元素关联的所有jQuery数据。 This method is useful when removed elements are to be reinserted into the DOM at a later time. 当删除的元素稍后要重新插入DOM时,此方法很有用。

Everything looks good for detach() to work with the toggle switch, except my efforts to implement it aren't working. 对于使用切换开关工作, detach()一切看起来都很好,除了我实现它的努力不起作用。

I've used the example on the jQuery website as a guide but it doesn't work on the grid. 在jQuery网站上使用了这个例子作为指南,但它不适用于网格。 I also read various related posts on this site, but to no avail. 我也阅读了这个网站上的各种相关帖子,但无济于事。 I must be missing something. 我肯定错过了什么。

Any feedback would be much appreciated. 任何反馈都将非常感激。

http://jsfiddle.net/tfyfpbb2/ http://jsfiddle.net/tfyfpbb2/

 $('.hide-divs').click(function() { $('.dolphin').toggleClass('hidden'); }) 
 .row { display: flex; flex-wrap: wrap; width: 500px; padding: 0; margin: 0; } .text { height: 50px; width: 100px; margin: 10px; padding-top: 15px; background: tomato; color: #fff; text-align: center; font-size: 2em; } .tile:nth-child(4n-7) .text { border: 2px solid #ccc; background-color: yellow; color: #000; } button { padding: 10px; background-color: lightblue; position: relative; left: 200px; } .hidden { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="row"> <div class="tile"> <div class="text">01</div> </div> <div class="tile"> <div class="text">02</div> </div> <div class="tile"> <div class="text dolphin">03</div> </div> <div class="tile"> <div class="text">04</div> </div> <div class="tile"> <div class="text">05</div> </div> <div class="tile"> <div class="text dolphin">06</div> </div> <div class="tile"> <div class="text">07</div> </div> <div class="tile"> <div class="text dolphin">08</div> </div> <div class="tile"> <div class="text">09</div> </div> <div class="tile"> <div class="text">10</div> </div> <div class="tile"> <div class="text">11</div> </div> <div class="tile"> <div class="text">12</div> </div> </div><!-- end .row --> <button type="button" class="hide-divs">HIDE DIVS 3, 6 &amp; 8</button> 

I suggest still using detach. 我建议仍然使用分离。 You can do so with this code: 您可以使用以下代码执行此操作:

var divs;

$('.hide-divs').on('click', function () {
    if(divs) {
        $(divs).appendTo('.row');
        divs = null;
    } else {
        divs = $('.dolphin').parent().detach();
    }
});

Then to ensure that the same order is used, I came up with this bit of code: 然后为了确保使用相同的顺序,我想出了这段代码:

$('.tile').each(function(i){
    $(this).data('initial-index', i);
});

...

$(divs).each(function(){
    var oldIndex = $(this).data('initial-index');
    $('.tile').eq(oldIndex).before(this);
});

Put it all together and we get this code: 把它们放在一起,我们得到这个代码:

var divs;

$('.tile').each(function(i){
    $(this).data('initial-index', i);
});

$('.hide-divs').on('click', function () {
    if(divs) {
        $(divs).appendTo('.row').each(function(){
            var oldIndex = $(this).data('initial-index');
            $('.tile').eq(oldIndex).before(this);
        });
        divs = null;
    } else {
        divs = $('.dolphin').parent().detach();
    }
});

Demo on jsfiddle: http://jsfiddle.net/tqbzff2v/2/ 关于jsfiddle的演示: http//jsfiddle.net/tqbzff2v/2/

Everyone was close, but here is exactly what you are looking for with your current html markup: http://jsfiddle.net/vs5o5nLb/2/ 每个人都很亲密,但这正是您正在寻找的当前HTML标记: http//jsfiddle.net/vs5o5nLb/2/

The trick is setting yourself up ahead of time with what you need to actually toggle, then keeping that information around to insert and detach from. 诀窍是提前设置自己实际切换所需的内容,然后保持信息的插入和分离。

var $els = $( '.tile' );
var stack = [];
var isShown = true;

$els.each(function() {
    var $this = $( this );
    if ( $this.find('.dolphin').length ) {
        stack.push({
            $el : $this,
            index : $els.index( this )
        });
    }
});

$('.hide-divs').click(function () {
    if ( isShown ) {
        $.each(stack, function() {
            this.$el.detach();
        });
        isShown = false;
    } else {
        $.each(stack, function() {
            $('.tile').eq( this.index ).before( this.$el );
        });
        isShown = true;
    }
});

I hope it helps. 我希望它有所帮助。

I have used remove() with toggle to remove and delete elements. 我使用了remove()和切换来删除和删除元素。 example: each time on mouse hover and check if text is printed in unordered list and then elements are removed on the next click. 示例:每次鼠标悬停并检查文本是否以无序列表打印,然后在下次单击时删除元素。 Jquery jQuery的

        $('h1').hover(function(){
                //alert('test toggle');
               remove_el();
               for(var i=0;i<5;i++){ 
               $('ul').append('<li>'+'END_check else'+i+'</li>').toggle();

                 }
               }

                );

            function remove_el(){

                $('li').remove();
            };

I'm not very sure if this what you'd like to do - http://jsfiddle.net/tfyfpbb2/1/ 我不太确定你是否愿意这样做 - http://jsfiddle.net/tfyfpbb2/1/

If so, you just need to add three row classes instead of one. 如果是这样,您只需要添加三个行而不是一个。 This way each row has it's own "space" and will not miss up the next row's styling. 这样每行都有自己的“空间”,不会错过下一行的样式。

<div class="row">
    <div class="tile">
        <div class="text">01</div>
    </div>

    <div class="tile">
        <div class="text">02</div>
    </div>

    <div class="tile">
        <div class="text dolphin">03</div>
    </div>

    <div class="tile">
        <div class="text">04</div>
    </div>
</div> 

Hope that helps! 希望有所帮助! Let me know if that's not what you wanted and I can edit my answer. 如果那不是您想要的,请告诉我,我可以编辑我的答案。

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

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