简体   繁体   English

jquery 选择器获取给定 div 中的所有锚元素,无论它们嵌套多深?

[英]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.我想将一个单击处理程序绑定到所有 a 标签。

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

On this line:在这条线上:

<div id="nest-one>

You've missed the closing double-quote on the id.您错过了 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.除此之外,确保任何引用 HTML 元素的 JavaScript 都在文档中准备好 function 和/或源中的这些元素之后。

Demo演示


EDIT编辑

per BoltClock's point:根据 BoltClock 的观点:

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.使用 $.live 或 $.delgate,这也将绑定到任何未来动态添加到 DOM 的元素。

example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM