我有一段代码,有时需要由脚本触发,但我不希望它更改我页面上的 URL。 (由于某些奇怪的原因,它弄乱了历史状态)
我需要触发的代码:
$(".photos-bottom .albums #albums li").live("click", function() {
// my action here
});
The code I use to trigger it:
$(".photos-bottom .albums #albums li:first").trigger("click");
要单击的链接,但是我刚刚注意到,它应该单击 li 并且 li 位于 href 内部,所以我不知道为什么它仍然单击它..
<a href="#/photos/1/album/42/" rel="address:/photos/1/album/42/">
<li id="42">
最佳答案
尝试triggerHandler()
相反:http://api.jquery.com/triggerHandler/
The .triggerHandler() method behaves similarly to .trigger(), with the following exceptions: The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission)... [omissis]
否则使用trigger()
带有 extraparameter
在调用中(请参阅 http://api.jquery.com/trigger/ )和处理程序中只需检查传递的参数。如果传递了参数,那么您将阻止默认链接操作。 <evt>.preventDefault()
(注意:我假设您的处理程序附加到 links 元素,而不是列表项,因为您无法将列表项包装到链接中)
关于javascript - 我可以触发单击 href 元素而不触发 href 链接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8985248/