开发者

How do I assign click handlers to each child with jquery?

<div id="menu开发者_Python百科">
    <div class="menuitem-on" id="home">Home</div>
    <div class="menuitem-off" id="mycart">My Cart</div>
    <div class="menuitem-off" id="shop">Shop</div>
</div>

how do I assign click handlers to each of the children of menu with jquery?


$("#menu").delegate('div','click', function(){
//do your thing here
});

Handler is on parent, so only one. You can add more div without changing code.

Here is a fiddle page to show a couple of different selector options to get the click anywhere, or just the first level. Shows the use of the event target, currentTarget as well: http://jsfiddle.net/8GLZJ/

Update 3/18/2013 for 1.9.1+ jQuery use:

$("#menu").on('click','div', function(){
//do your thing here
});


You don't want to do that because:

  • You create a event handler for each children
  • If you dynamically add more elements, the handler won't work for them.

A better solution is to add a single event handler to the parent element and then do a different action based on the event.target property, that contains the clicked element.

This happens because of event bubbling and it's a cool feature you should take advantage of.

jQuery in particular abstracts this under what they call live events so you should go with those.


$("#menu div").click(function(){
   // your code goes here
   // $(this) give you the element that was clicked
});


Binding event to each one of element using click() or bind('click', ...) isn't a good solution, because in case if you have, lets say 50 items, you will have to bind 50 same handlers - browser has to register them all.

Better solution is to use feature called event delegation - and jQuery has special method for that - delegate(). So your code will look like this:

$('#menu').delegate('div', 'click', function() {
    //code of your handler - 'this' refers to clicked element
});

There is an article with video showing difference between click, live and delegate in jQuery: NetTuts+.


Something like

$("#menu div").on('click', function(){
    //alert('clicked');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜