开发者

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

开发者 https://www.devze.com 2023-01-19 00:00 出处:网络
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?

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

精彩评论

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

关注公众号