最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery .trigger('click') - Stack Overflow

programmeradmin0浏览0评论

I am having trouble getting this to work. I would like to trigger the second link. If anyone can help that would be much appreciated.

    $(".links").click(function () {
        alert($(this));
    })


    function someFunction(){
        $(".links").trigger('click');
    }

    someFunction();

    ...
    <a href="1.html" class="links">One</a>
    <a href="2.html" class="links">Two</a>
    <a href="3.html" class="links">Three</a>

I am having trouble getting this to work. I would like to trigger the second link. If anyone can help that would be much appreciated.

    $(".links").click(function () {
        alert($(this));
    })


    function someFunction(){
        $(".links").trigger('click');
    }

    someFunction();

    ...
    <a href="1.html" class="links">One</a>
    <a href="2.html" class="links">Two</a>
    <a href="3.html" class="links">Three</a>
Share Improve this question asked Oct 20, 2010 at 14:39 Chris ChieraChris Chiera 751 gold badge2 silver badges9 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

Have someFunction() accept an argument that is the 0 based index of link you want to click.

function someFunction( n ){
    $(".links:eq(" + n + ")").trigger('click');
}

someFunction( 1 ); // Pass 1 to trigger the second link

This uses the :eq() selector. You could also use the .eq() method if you wanted.

function someFunction( n ){
    $(".links").eq( n ).trigger('click');
}

To trigger for the second link only:

$(".links").eq(1).trigger('click');

.eq(n) reduce the set of matched elements to the one at the specified index. The index is zero based.

The above solutions did not work for me.

But this solution works for me.

$('#elementID').click(function () {
    //some stuff
});

I need trigger to work when the page is loaded.

$( document ).ready(function() {
    $('#elementID').trigger('click');
});

OR

If you do not need to run when the page is loaded, you can use it in the function.

function someFunction(){
    $('#elementID').trigger('click');
}
发布评论

评论列表(0)

  1. 暂无评论