jquery 强制点击 (href)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5838241/
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
jquery force click (href)
提问by agis
I have this:
我有这个:
<li>
<a href="#" data-content="visit">
<span class="bf_hover"></span>
<span>Visit us</span>
</a>
</li>
And I want to automatically open the "Visit Us" link.
我想自动打开“访问我们”链接。
How I can do this ?
我怎么能做到这一点?
回答by Hussein
You can trigger a click by doing
您可以通过执行以下操作触发点击
$('li a').trigger('click');
回答by LuckyBrain
It looks like jQuery is not able to force the click event for hyperlinks in 100% of the cases and yours is probably one of those. My way to solve this issue is using the following:
看起来 jQuery 无法在 100% 的情况下强制超链接的点击事件,而您的可能就是其中之一。我解决这个问题的方法是使用以下方法:
$('li a')[0].click();
This way, you use it as a DOM element and not as a jQuery object, and it seems to work in many browsers.
这样,您就可以将它用作 DOM 元素而不是 jQuery 对象,而且它似乎可以在许多浏览器中使用。
回答by Fernando Gomez
set the windows location to the href of the link. Forcing a click will only work if the link is bound to a click event listener. The default behavior of a link is to go to a location when clicked, but a click event listener is not added. Your solution should be the following:
将窗口位置设置为链接的 href。强制单击仅在链接绑定到单击事件侦听器时有效。链接的默认行为是单击时转到某个位置,但未添加单击事件侦听器。您的解决方案应该如下:
<li>
<a id="mylink" href="#" data-content="visit">
<span class="bf_hover"></span>
<span>Visit us</span>
</a>
</li>
<script>
window.location = $("#mylink").attr("href");
</script>
回答by TheBentArrow
One possibility would be to replace the pound sign in href="#" with the link to the page you would like to take your users, i.e.
一种可能性是将 href="#" 中的井号替换为您希望为用户提供的页面链接,即
<li>
<a href="visit_us.html" data-content="visit">
<span class="bf_hover"></span>
<span>Visit us</span>
</a>
</li>
Where "visit_us.html" is the link to the page.
其中“visit_us.html”是该页面的链接。