Javascript 如何在页面加载时使用 jquery 触发点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14575852/
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
How to trigger Click as a page loads using jquery
提问by TJ Sherrill
I have seen a ton of posts about this, but none worked as I was trying to.
我看过很多关于这个的帖子,但没有一个像我想要的那样工作。
$(document).ready(function() {
$('#link_to_content').tigger('click');
});
Once the page is loaded I want to trigger the click. I know its weird to open a link once a page loads but in this case it makes sense.
加载页面后,我想触发点击。我知道在页面加载后打开链接很奇怪,但在这种情况下是有道理的。
I am using jquery 1.7
我正在使用 jquery 1.7
回答by qbantek
should be:
应该:
$(document).ready(function() {
$('#link_to_content').trigger('click');
});
working example here: http://jsfiddle.net/zpnQv/
这里的工作示例:http: //jsfiddle.net/zpnQv/
EDIT:
编辑:
if you want to follow the link you could do something like:
如果您想点击链接,您可以执行以下操作:
HTML:
<a href="http://www.yahoo.com/" id="link_to_content">Click Me</a>
JS:
$(document).ready(function () {
$("#link_to_content").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
alert("going to " + href);
window.location = href;
});
$('#link_to_content').trigger('click');
});
Example: http://jsbin.com/omudih/1/
回答by rockerest
jQuery won't click on links. My own interpretation is that this is a bit of a security risk, which is more or less what the linked answer boils down to.
jQuery不会点击链接。我自己的解释是,这有点安全风险,这或多或少可以归结为链接的答案。
However, as the linked answer states, you can simply select the Javascript HtmlDOMElementand .click()it.
但是,正如链接的答案所述,您只需选择 JavascriptHtmlDOMElement和.click()它即可。
In other words: $('#link_to_content')[0].click();
换句话说: $('#link_to_content')[0].click();
回答by shefali
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() {
$("#link_to_content").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() 处理程序被调用后立即运行。
OR
或者
use trigger in call back function of .load();
在 .load() 的回调函数中使用触发器;
you can also use .on() instead of trigger()
你也可以使用 .on() 而不是 trigger()
$('div_to_load').load("#link_to_content",function(){
$("#link_to_content").trigger('click');
});
.on() example
.on() 示例
$('div_to_click').on("click",".title",function(){
alert('sdfdsf');
});

