Jquery选择孩子中的所有孩子

时间:2011-08-05 17:06:21

标签: javascript jquery selector

我确信这将是一个简单的问题,但我仍然在使用Jquery中的DOM选择器,所以这里是我的html代码的模型:

<fieldset class="product-options" id="product-options-wrapper">
   <ul class="options-list">
      <li><a href>Item1.1</a></li>
      <li><a href>Item1.2</a></li>
      <li><a href>Item1.3</a></li>
   </ul>

   ...other html items here

   <ul class="options-list">
      <li><a href>Item2.1</a></li>
      <li><a href>Item2.2</a></li>
      <li><a href>Item2.3</a></li>
   </ul>

</fieldset>

现在,如何选择具有类名.options-list的两个列表(或X个列表)中的所有'li a'项,并使用单击函数绑定它们。

目前我有:

$('fieldset#product-options-wrapper ul.options-list > li a').bind('click', function(e) {
     //code here
});

它只获得第一个选项列表。

谢谢,非常感谢!

编辑:如果我先点击Item2.X列表项,那么它将获取该选项列表。但是一旦我点击Item1.x列表项,它就会忽略第二个.options-list

4 个答案:

答案 0 :(得分:1)

$('.options-list a').bind('click', function(e) { });怎么样?

答案 1 :(得分:1)

如果你要绑定到每个li元素,你应该将它绑定到ul元素(当有很多事件时,它会大大提高性能)。

$('.options-list', '#product-options-wrapper').bind('click', function(e)
{
   e.preventDefault();//In case you don't want to go to a different page
   var clicked = e.target;//The href that was clicked
   /* If you only want this to happen if the a tag was clicked, add the following line
   if(clicked.tagName == 'A')*/
   //Rest here
});

答案 2 :(得分:0)

在这种情况下,您可以使用委托使其更简单。试试这个

$('#product-options-wrapper ul.options-list').delegate('li > a', 'click', function(e) {
     //code here
});

答案 3 :(得分:0)

你的方法对我来说似乎很合理。我使用你的HTML创建了一个测试小提琴(以及一个额外的锚来证明它不会被添加点击)和你的JS(稍加修改)。

http://jsfiddle.net/chrisvenus/esZxH/1/

你做过的选择器确实有效,但既然你说你希望a成为李的直接孩子(或者至少我是这样读的)我在上面的版本中略微调整了它。你确定它不仅仅是你的功能在执行时没有做到你想要的功能,还是你可以确认你的点击功能根本没有运行?