HTML <a> Native Click Event
Is there a way to programmatically within javascript call the native click event of an tag? The .trigger('click') or .click() functions will not work, because they are triggering the onClick event of the link and not the event that follows the URL. I need to programmatically click a hidden link and follow that link to a new tab within the same browser. Window.开发者_如何学Goopen won't work either because that will cause a popup and I am trying to avoid that. I need this, because I am dynamically generating a URL on the server side and sending the responds back via JSON. I then populate the HREF attribute of the hidden link with the resulting URL. If I can get an answer on how this can be done, I would greatly appreciate it.
If you're populating a HREF with the JSON response, why not just store it in a variable instead, and when you want to go to it, window.location = yourVariable;
?
Unless you want this to work on IE only, I don't have an answer for you, but I can tell you what the problem is. The problem is target=_blank
. Try the following code as a test--notice it will bring you to Google.com--then try writing "_blank" in as the target. That seems to be the only thing that the browsers won't allow. A partial answer to your question is fireEvent()
works with IE and dispatchEvent()
works with everything else. If anyone else could improve on this code, I would appreciate a better answer as well.
<html>
<head>
<script type="text/javascript">
window.onload = function fireElement() {
var target=document.getElementById('foobar');
if(document.dispatchEvent) { // W3C
var oEvent = document.createEvent( "MouseEvents" );
oEvent.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, target);
target.dispatchEvent( oEvent );
}
else if(document.fireEvent) { // IE
target.fireEvent("onclick");
}
}
</script>
</head>
<body>
<div>
<a id="foobar" target="" href="http://www.google.com"></a>
</div>
</body>
</html>
From what I can tell, it is not possible to call the native click function of a link through javascript. You can reference the onclick by using .click(), but the native click will still run before that is called. So, if you wanted to alter the link before following it when you click the link, you would have to click the link twice before it would send you to the altered link.
精彩评论