2017-05-14 36 views
0

點擊後,用UL LI替換div後,我怎麼能刪除當我再次單擊按鈕,並重復每次點擊過程?我需要保持原有的UL李在DOM中,所以不能追加,需要克隆拆卸或刪除後,使用replaceWith,但使其切換

$("#button").click(function() { 
 
    $("#button").toggleClass("newClass"); 
 
    $("div").replaceWith($("ul li")); 
 
    if ($("#button").text() == "ADD UL LI TO DIV") { 
 
    $("#button").text("REMOVE DIV CONTENT"); 
 
    } else { 
 
    $("#button").text("ADD UL LI TO DIV"); 
 
    } 
 
});
#button { 
 
    cursor: pointer 
 
} 
 

 
#button { 
 
    background: red 
 
} 
 

 
#button.newClass { 
 
    background: green 
 
} 
 

 
ul { 
 
    display: none 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li>1</li> 
 
    <li>2</li> 
 
    <li>3</li> 
 
    <li>4</li> 
 
    <li>5</li> 
 
</ul> 
 
<span id="button">ADD UL LI TO DIV</span> 
 
<div></div>

+0

你想在div和ul之間切換嗎? – julekgwa

+0

不,我想克隆裏面的「李」,並附加到一個div,然後切換到顯示/隱藏與李黎內容的div – MShack

+0

張貼整個例子在這裏,而不是在遠程站點。您可以使用[Stack Snippets](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/)使其可執行。 – Barmar

回答

1

function f1() { 
 
    $("ul").clone().appendTo("div"); 
 
    $("div ul").css("display", "block"); 
 
    $("#button").addClass("newClass").text("REMOVE DIV CONTENT"); 
 
    $(this).one("click", f2); 
 
} 
 

 
function f2() { 
 
    $("div").empty(); 
 
    $("#button").removeClass("newClass").text("ADD UL LI TO DIV"); 
 
    $(this).one("click", f1); 
 
} 
 
$("#button").one("click", f1);
#button { 
 
    cursor: pointer; 
 
    background: red; 
 
} 
 

 
#button.newClass { 
 
    background: green 
 
} 
 

 
ul { 
 
    display: none 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul> 
 
    <li>1</li> 
 
    <li>2</li> 
 
    <li>3</li> 
 
    <li>4</li> 
 
    <li>5</li> 
 
</ul> 
 
<span id="button">ADD UL LI TO DIV</span> 
 
<div></div>

我相信這是你所需要的。

+0

謝謝,這是我需要的 – MShack