开发者

jquery selector to get all anchor elements within a given div, no matter how deeply they are nested?

suppose some markup such as:

<div id="header">
   <div id="nest-one>
      <a href="#">one</a>
      <div id="nest-two">
         <a href="#">two</a>
         <a href="#">three</a>
       </div>
    </div>
</div>

and I want to tie a single click handler to all of the a tags.

I tried the following, but didn;t seem to work. I know I'm missing som开发者_StackOverflowething stupid easy, just not sure what it is.

$('#header a').click(function(){alert('on click')});


On this line:

<div id="nest-one>

You've missed the closing double-quote on the id.

Aside from that, make sure any JavaScript referencing HTML elements is in the document ready function and/or after those elements in the source.


Demo


EDIT

per BoltClock's point:

This works actually

$('#header a').click(function(){alert('on click')});


Use $.live or $.delgate, this will also bind to any future elements added dynamically to the DOM.

example:

$("#header").delegate("a", "click", function() {
  console.log("%o clicked", this ); // log object in firebug
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜