I came across a curiosity in jQuery: if I call .click()
on a link the click
event handlers are called, but the link isn't actually followed (as if it were clicked in the browser):
<a id="link" href="http://www.google.com>Link</a>
$("#link").click() // won't take me to Google
But in plain Javascript, everything behaves as expected:
document.getElementById("link").click() // *will* take me to Google
This is apparently intentional behaviour - but I'm struggling to work out why click
was implemented like this - with a special exception for links?
Fiddle here: http://jsfiddle.net/9a6sp/
To clarify: I'm not asking how to click link in JS, but rather, why the default behaviour in jQuery is effectively that links aren't clicked when you call .click()
domelement.click()
isn't supported cross browser for redirecting. If you need to redirect to the location in a link you can use:
window.location = $('#link').prop('href');
jQuery.click() is meant to bind a click handler to an element. However it can be used to trigger a click() event bound using jQuery.
jQuery.trigger() will trigger a bound event handler, such as $(someElement).trigger("click");
If you wanted to trigger a link in jQuery may I suggest the following.
$(someelement).click(function () {
window.location = $(link).attr("href");
});
Maybe this is what you are looking for? First, you need to attach a click event. then you can use trigger to fire it.
<html>
<head title="jQuery Test">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#blah').click(function () {
alert('clicked');
});
$('#blah').trigger('click');
});
</script>
</head>
<body>
<a id="blah" href="#">BLAH</a>
</body>
</html>
For why this isn't work, in jsFiddle $('#link')
doesn't select the anchor in html, and click()
fails. Even the type selector $('a').href
fails.
http://jsfiddle.net/yangchenyun/L9EUS/
The code works in normal browser. I have tested the code on stackoverflow.com with this code
jQuery('a').eq(1).click()
in chrome concole, it triggers the click()
on the logo.
So in conclusion, click() links work in jQuery(). jsfiddle.net has interrupts the normal jQuery function.
I'm just guessing as to why the jQuery team chose to implement things this way, since I'm not on the jQuery team, but the navigation aspect of an anchor tag can be triggered by other UI behaviors than just clicking with the mouse. For example in plain old javascript, using the keyboard to activate an element doesn't trigger the onClick action, but it will trigger the navigation action of an anchor tag.
In other words, by clicking on a link you're just using one of several possible mechanisms for navigating to the referenced endpoint, but the navigation and the click aren't the same event, so jQuery chose to treat the click just that.
来源:https://stackoverflow.com/questions/8126590/why-cant-i-click-links-in-jquery