最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to I undo .detach()? - Stack Overflow

programmeradmin6浏览0评论

I'm using JQuery 1.5 and the following code to detach li elements w/ a certain class when a button is clicked. What I want to know is, when that button is clicked again, how do I add the element back onto the page?

    <script>
    $("#remove").click(function () {
      $('li.type').fadeOut(300, function() { $(this).detach(); });
    });</script>

I'm using JQuery 1.5 and the following code to detach li elements w/ a certain class when a button is clicked. What I want to know is, when that button is clicked again, how do I add the element back onto the page?

    <script>
    $("#remove").click(function () {
      $('li.type').fadeOut(300, function() { $(this).detach(); });
    });</script>
Share Improve this question asked Apr 23, 2011 at 12:52 binaryorganicbinaryorganic 1,5944 gold badges17 silver badges25 bronze badges 4
  • This is a good question, however, your lack of acceptance is disturbing. People who might know are not as forgiving as I am. Please accept some answers before asking new questions. :) (no bad feelings however) – Caspar Kleijne Commented Apr 23, 2011 at 12:56
  • 2 Why detaching it and not just hiding it? Otherwise you have to keep a reference to the element. – Felix Kling Commented Apr 23, 2011 at 13:02
  • @Felix, I'm using nth-of-type(odd) and (even) in my style sheet to position elements differently. When I use .hide the odd/even status of the hidden element is retained, messing up the placement of everything else. .detach fixes this, but I don't know how to bring the element back in this way. – binaryorganic Commented Apr 23, 2011 at 13:05
  • @felix, .remove() fixes my style issue as well, but I figured I'd have better luck getting .detach to e back. Maybe I'm wrong? – binaryorganic Commented Apr 23, 2011 at 13:06
Add a ment  | 

2 Answers 2

Reset to default 7

The question is: where on the page do you want to put the element back? If, for example, all the li elements go back inside <ul id="foo"></ul> you might use something like this:

var items = [];
$('li.type').fadeOut(300, function() {
     items.push( $(this).detach() );
});

$('#replace').click(function() {
    for(var i = 0; i < items.length; i++) {
        $("ul#foo").append(items[i]);
    }
    items = [];
});

here u can't for loop.

var demo;
$('li.type').fadeOut(300, function() {
     demo = $(this).detach();
});

$('#replace').click(function() {
   $("ul#foo").append(demo);
});
发布评论

评论列表(0)

  1. 暂无评论