简体   繁体   中英

Select all children of last div with Jquery?

I'm creating a jQuery menu that, when a user clicks a .item div on the last .menu div, another .menu div should be created below with other .item divs. Then, only those divs may be clicked (if there are any) to possibly generate other .menu divs (with possibly another .item divs).

Basically, I need the jQuery selector which selects all .item divs inside last .menu div only.

I tried the following with no success:

$('.menu:last').children('.item').on("click",function(){
  $('body').append("<div class=\"menu\"><div class=\"item\"><svg><text x=\"50%\" y=\"50%\" dy=\".3em\">Vehicles</text></svg></div></div>");
});

and this did not work as well:

$('.menu:last-child .item').on("click",function(){
  $('body').append("<div class=\"menu\"><div class=\"item\"><svg><text x=\"50%\" y=\"50%\" dy=\".3em\">Vehicles</text></svg></div></div>");
});

Here is the fiddle with the html and css code:

http://jsfiddle.net/2ZpGe/

Any suggestions?

If you want the click to be dynamically on the last menu you must use event-delegation like this

$(document).on('click','.menu:last .item',function(){
          $('body').append("<div class=\"menu\"><div class=\"item\"><svg><text x=\"50%\" y=\"50%\" dy=\".3em\">Vehicles</text></svg></div></div>");
});

DEMO

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