简体   繁体   中英

How can I combine .toggleClass() with .appendTo()?

I append a new class to a HTML container. How can I toggle this on/off by clicking on the menu button? And is it even "best practice" to write more complex HTML code in JavaScript or would you prefer another method for this? Because I plan to do this for some more containers. Thank you!

$(document).ready(function() { 
    $( "a.header-login" ).click(function() {
        $("<div class='sub-menu'>" +
        "<h2>Hi x!</h2>"+ 
        "<a class='item' href='#'>Logout</a>"+ 
        "</div>")
        .appendTo("header .header-r");
    })
});

I want to accomplish that another click on "a.header-login" deletes the container ".sub-menu". Now, it is always generated when you click "a.header-login"

In this case you need to add a condition to check whether or not the element already exists. If it doesn't create it, if it does remove it.

jQuery(function() {
  $('a.header-login').click(function() {
    var $target = $('header .header-r .sub-menu');
    if ($target.length === 0) {
      $('<div class="sub-menu"><h2>Hi x!</h2><a class="item" href="#">Logout</a></div>').appendTo('header .header-r');
    } else {
      $target.remove();
    }
  })
});

That being said, you can make this much simpler logic if you always include the .sub-menu in the HTML of your page but hide it with CSS by default. In that case your jQuery would become a simple call to toggle() :

jQuery(function() {
  $('a.header-login').click(function() {
    $('header .header-r .sub-menu').toggle();
  })
});

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