简体   繁体   中英

jquery click append and remove append second click

I am trying to make a append menu on click div. But i have one question here. How can i remove appended elements after second click. Anyone can help me in this regard ?

This is the DEMO page from codepen.io

Js

$(document).ready(function(){
   $("body").on("click", ".menu-button", function(event){
      event.preventDefault();
      $(".menu-container").append('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading&#8230; </span></div></div>');
   });

});

Seems like toggling the element instead of adding it would be better, but you could just put a check

var childNodes = $(".menu-container").children();
if (childNodes.length) {
    childNodes.remove();
} else {
    $(".menu-container").append("...");
}

Append the content only if the content not exist.

$(document).ready(function() {

   $("body").on("click", ".menu-button", function(event) {
      event.preventDefault();
      if (!$('.button').length) {
         $(".menu-container").append('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading&#8230; </span></div></div>');
      } else {
         $(".menu-container").html(''); // Empty after 
      }
   });

});

Here's another solution I've called the dblclick event to empty the contents of the menu-container .This empties the entire div.Incase you want to remove the last child, you can find the length and remove the last one that way.

$("body").on("dblclick", ".menu-button", function(event){
         $(".menu-container").empty();
     });

Working Demo

By no means the most elegant solution but probably the easiest:

$(document).ready(function(){
   $("body").on("click", ".menu-button", function(event){
      event.preventDefault();
      if($('.menu-container').html().length > 0) {
         $(".menu-container").html(null)
      }
      else {
         $(".menu-container").html('<div class="button"></div><div class="rebackbar"></div><div class="abc" id="myDiv"></div><div class="lBrgF"><div class="card"><span class="three-quarters-loader">Loading&#8230; </span></div></div>');
      }
   });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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