admin管理员组

文章数量:1327929

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
});

本文标签: