javascript jQuery .trigger('点击')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3979041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:52:48  来源:igfitidea点击:

jQuery .trigger('click')

javascriptjquery

提问by Chris Chiera

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>

回答by user113716

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

someFunction()接受的说法是链接的,你要点击0的索引。

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()methodif you wanted.

它使用:eq()选择。如果需要,您也可以使用.eq()方法

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

回答by Arrix

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.

.eq(n) 将匹配元素的集合减少到指定索引处的元素。该指数从零开始。

回答by Tolga

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');
}