开发者

jQuery Find not working for :first

I am trying to find some child a elements within a ul parent. But, I need to only find the first a. Here is what I am using

$('div.item a').click(function() {
    $(this).parent().next('ul.subItems').find('a:first').addClass('selected');
});

HTML:

<div class="item"><a id="main5830" href="http://www.mysite.com">Test</a></div>
<ul class="subItems">
<li><a>test 1</a></li>
<li><a>test 2</a></li>
<li><a>test 3</a></li>
</ul>

I would like test 1's a element to get the class of selected.

For some reason, this is not selecting the first a within in the UL, or ANYTHING in the UL ele开发者_运维问答ment. Have I done something wrong here?


It does work, just need to use return false; (or event.preventDefault();) at the end of the click event handler to prevent the anchor default click behaviour.

$('div.item a').click(function() {
    $(this).parent().next('ul.subItems').find('a:first').addClass('selected');
    return false;
});

or

$('div.item a').click(function(e) {
    e.preventDefault();
    $(this).parent().next('ul.subItems').find('a:first').addClass('selected');
});

Here's a Working Demo showing it working

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜