Javascript 如何触发点击页面加载?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2060019/
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-08-22 22:37:08  来源:igfitidea点击:

How to trigger click on page load?

javascriptjquery

提问by Justine

I'm looking for a way to automatically "click" an item when the page loads.

我正在寻找一种在页面加载时自动“单击”项目的方法。

I've tried using

我试过使用

$("document").ready(function() {
    $("ul.galleria li:first-child img").trigger('click');
});

but it doesn't seem to work? However, when I enter $("ul.galleria li:first-child img").trigger('click');into Firebug's console and run the script, it works.

但它似乎不起作用?但是,当我进入$("ul.galleria li:first-child img").trigger('click');Firebug 的控制台并运行脚本时,它可以工作。

Can the trigger event be used on load?

可以在加载时使用触发事件吗?

回答by noah

The click handler that you are trying to trigger is most likely also attached via $(document).ready(). What is probably happening is that you are triggering the event before the handler is attached. The solution is to use setTimeout:

您尝试触发的点击处理程序很可能也通过$(document).ready(). 可能发生的情况是您在附加处理程序之前触发了事件。解决方案是使用setTimeout

$("document").ready(function() {
    setTimeout(function() {
        $("ul.galleria li:first-child img").trigger('click');
    },10);
});

A delay of 10ms will cause the function to run immediately after all the $(document).ready()handlers have been called.

10 毫秒的延迟将导致函数在所有$(document).ready()处理程序被调用后立即运行。

回答by Steven

$(function(){

    $(selector).click();

});

回答by Mark Schultheiss

$("document").ready({
    $("ul.galleria li:first-child img").click(function(){alert('i work click triggered'});
}); 

$("document").ready(function() { 
    $("ul.galleria li:first-child img").trigger('click'); 
}); 

just make sure the click handler is added prior to the trigger event in the call stack sequence.

只需确保在调用堆栈序列中的触发事件之前添加点击处理程序。

  $("document").ready(function() { 
        $("ul.galleria li:first-child img").trigger('click'); 
    }); 

   $("document").ready({
        $("ul.galleria li:first-child img").click(function(){alert('i fail click triggered'});
    }); 

回答by Ankit Kashnia

try this,

尝试这个,

$("document").ready(function(){

$("your id here").trigger("click");
});

回答by Krish Bhanushali

You can do the following :-

您可以执行以下操作:-

$(document).ready(function(){
    $("#id").trigger("click");
});