最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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 something stupid easy, just not sure what it is.

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

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 something stupid easy, just not sure what it is.

$('#header a').click(function(){alert('on click')});
Share Improve this question asked Aug 17, 2011 at 1:28 shsteimershsteimer 28.8k30 gold badges80 silver badges95 bronze badges 1
  • 3 Is that line of JavaScript in the document ready, or at least after the HTML in the source? – nnnnnn Commented Aug 17, 2011 at 1:31
Add a ment  | 

3 Answers 3

Reset to default 5

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)

  1. 暂无评论