触发单击链接不会更改位置哈希 [英] Triggering click on a link doesn't change location hash
问题描述
我正在开发一个在某些情况下使用 onHashChange
事件监听器并使用 href =#hash手动点击链接的Web应用程序
运作良好。
但是当我触发时使用jQuery的 $('a [href =#hash]')点击相同的链接。触发器('click')
或者 $('a [href =#hash]')。click()
地址栏中的哈希值没有变化。
I'm working on a web application that uses onHashChange
event listener in some situations and manually clicking on a link with href="#hash"
works perfectly well.
But when I trigger click on the same link using jQuery's $('a[href=#"hash"]').trigger('click')
or $('a[href=#"hash"]').click()
hash in address bar is not changing.
我做错了吗?或者我为此目的使用另一种方法?
Is it something that I'm doing wrong? or I shoud use another method for this purpose?
HTML
<a href="#hash">Do Something</a>
JS
// Not working
$('a[href="#hash"]').click();
// Not working
$('a[href="#hash"]').trigger('click');
推荐答案
你写的是真的(它足以调试jQuery源代码):触发器点击事件对锚点不起作用。
What you wrote is true (it's enough to debug jQuery source code): the trigger click event doesn't work on an anchor.
为了实现您的尝试,您可以获取dom元素然后触发单击:
In order to achieve what you are trying you can get the dom element and then fire the click:
$('a[href="#hash"]').get(0).click()
这只会起作用。
这篇关于触发单击链接不会更改位置哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!