开发者

How to detect the 2nd link on a page using jQuery?

The first one below works, that is a:first detects the 1st link, but a:second doesn't. How can I detect the 2nd link on a page using jQuery?

<script type="text/javascript">
    $(document).ready(function() {

        $('a开发者_如何学运维:first').click(function() {
            alert('you clicked 1st link');
        });

        $('a:second').click(function() {
            alert('you clicked 2nd link');
        });

    });
</script>

<a href="#">1st Link</a>
<a href="#">2nd Link</a>


You use eq(), like so:

$('a').eq(1).click(...);

Or the selector version:

$('a:eq(1)').click(...);

It is 1 because eq is 0-based.


You can use :eq(1) like this:

$('a:eq(1)').click(function() {
  alert('you clicked 2nd link');
});

You can test it here. Or .eq(1) like this:

$('a').eq(1).click(function() {
  alert('you clicked 2nd link');
});

Test that version here. Unlike :nth-child(), the eq versions are for the index, which is 0-based.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜