I a开发者_JAVA技巧m having anchor tag in my page. I like to trigger click event onload . Which means I wanna open this page "http://XXXXX.com" with new tab. Because I don't wanna popup blockers. Is there anyway to do this?
anchor attrs are given bellow
id="add_redirect"
href="http://XXXXX.com"
target="_blank"
Yeah, you can use a click event called onLoad()
. Just use the setTimeout()
method in jquery. It will call a click function without clicking it. Here is an example:
$("document").ready(function() {
setTimeout(function() {
$("#add_redirect").trigger('click');
},10);
});
This will work for you when the page start to load and the time delay is 10ms which is negligible. Syntax has been corrected.
Try adding the following code in the page load
document.getElementById('add_redirect').click();
Using JQuery you can do that pretty easy. The earlier posted solution also work of course.
$(document).ready(function(){
$("#add_redirect").trigger('click');
});
TRY DEMO
If your goal is to bypass pop-up blockers on page load, triggering the click
event synthetically probably won't work. Browsers are smart enough to know when a click
is user-generated vs. when you've called the click
function on the DOM element (on those browsers were that even works). Examples: http://jsbin.com/avibi3/3, http://jsbin.com/avibi3/4
Using jQuery's trigger
mechanism certainly won't do it, because it doesn't really trigger a click
event at all; it just fires the handlers that jQuery hooked up (edit: and, apparently, ones defined via an onclick
attribute — see Sukhi's answer — but not ones attached via addEventListener
). If that's what you want to do, Sukhi's answer shows you how, although I always say: If you want code to be run from two different places, put it in a function, and call that function from two different places (rather than putting it in a click
handler and then simulating a click just to run the code). There are valid use cases for trigger
(mostly relating to integrating with third-party scripts), but for running your own code from two different places, it's a symptom of a design problem.
精彩评论