Why can#39;t I click() links in jQuery?(为什么我不能在 jQuery 中单击()链接?)
问题描述
我在 jQuery 中遇到了一个好奇心:如果我在链接上调用 .click()
,则会调用 click
事件处理程序,但实际上并没有遵循该链接(就像在浏览器中点击一样):
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
但在纯 Javascript 中,一切都按预期运行:
But in plain Javascript, everything behaves as expected:
document.getElementById("link").click() // *will* take me to Google
这显然是 故意行为 - 但我正在努力找出为什么 click
是这样实现的 - 链接有一个特殊例外?
This is apparently intentional behaviour - but I'm struggling to work out why click
was implemented like this - with a special exception for links?
在这里提琴:http://jsfiddle.net/9a6sp/
澄清一下:我不是在问如何在 JS 中单击链接,而是为什么 jQuery 中的默认行为实际上是当您调用 .click 时链接没有被单击()
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()
不支持跨浏览器重定向.如果您需要重定向到链接中的位置,您可以使用:
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 中单击()链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!