页面加载后如何触发点击事件?

59
我正在寻找一种在页面加载时自动“点击”一个项目的方法。 我已经尝试过使用:
$("document").ready(function() {
    $("ul.galleria li:first-child img").trigger('click');
});

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

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


它应该可以工作,除非元素稍后添加。你能发布一个演示吗?(尝试使用http://jsbin.com) - SLaks
你能否提供需要执行此操作的场景?听起来像是强制性 JavaScript。 - Perpetualcoder
你的 click 处理程序添加在哪里? - SLaks
它使用jQuery Galleria插件(http://devkick.com/lab/galleria/)从图像的无序列表创建画廊。我正在尝试在页面加载时触发大图像,而不必点击缩略图。 - Justine
这是我的脚本文件:http://dev.gentlecode.net/blossomsoft/js/scripts.js - Justine
5个回答

136

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

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

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

或者你可以检查元素是否准备就绪:

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

1
一个非jQuery的解决方案会很棒。 - Matej
不错。很奇怪它按顺序运行,但仍然缺少声明。这个解决了我的问题。 - Robert McMahan
你的回答帮助了我解决这个问题:http://stackoverflow.com/questions/39215964/why-window-load-isnt-working-when-the-request-comes-from-outside-the-page-but/ 非常感谢。 - Luis
首先感谢您。但是为什么第二种解决方案(检查元素是否准备就绪)不起作用呢?您能再详细解释一下吗?谢谢:] - hayley

7
$(function(){

    $(selector).click();

});

2
API 参考:http://docs.jquery.com/Events/click。 请注意 $(回调) 相当于 $(“document”).ready(callback); - Steven
1
相同的效果 - 在Firebug中可以工作,但是当输入到我的脚本文件中时,它就不起作用了。Firebug也没有给出任何错误。是否有其他脚本在$(function() { .. });中的文件中会有影响呢? - Justine

6
$("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'); 
}); 

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

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

你的回答是最合适的。谢谢。 - Foreever

2
您可以执行以下操作:-
$(document).ready(function(){
    $("#id").trigger("click");
});

0

试试这个,

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接