我可以触发单击 href 元素而不触发 href 链接吗?
我有一段代码,有时需要由脚本触发,但我不希望它更改我页面上的 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">
I have a piece of code that will sometimes need to be triggered by a script, but I don't want it to change the URL on my page. (it messes up the history state for some odd reason)
The code I need to trigger:
$(".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");
The link to click, however I just noticed, it's suppose to click the li and the li is inside of the href so i don't know why it's still clicking it..
<a href="#/photos/1/album/42/" rel="address:/photos/1/album/42/">
<li id="42">
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
triggerHandler()
代替: http://api.jquery.com/triggerHandler/< /a>否则使用.preventDefault()
trigger()
和调用中的额外参数
(请参阅http://api.jquery.com/trigger/ )并在你的处理程序中只需检查传递的参数即可。如果传递了参数,那么您将阻止默认链接操作。(注意:我假设您的处理程序附加到 links 元素,而不是列表项,因为您无法将列表项包装到链接中)
try
triggerHandler()
instead: http://api.jquery.com/triggerHandler/Otherwise use
trigger()
with anextraparameter
in the call (see http://api.jquery.com/trigger/) and in your handler just check the arguments passed. If a parameter was passed then you will prevent the default link action with.<evt>.preventDefault()
(note: I assume you handler is attached to links element, not to the list item, since you cannot wrap a list item into a link)
我认为这是由 live() 引起的。这是因为事件向上冒泡到
并触发
上的点击事件。您可以使用 delegate() 或 on() (jQuery > 1.7) 将事件处理程序附加到
上,然后从函数返回 false 以阻止它触发重定向
您可以 与委托一起使用
Fiddle http://jsfiddle.net/3CQFK/
I think this is caused by live(). This is because the events bubble up to the
<body>
and triggers the click event on the<a>
. You could use delegate() or on() (jQuery > 1.7) to attache the event handler on the<a>
and then return false from the function to stop it from triggering the redirectYou could do
Fiddle working with delegate http://jsfiddle.net/3CQFK/
是的,这是一个正常的任务。您可以在回调收到的事件上调用一个函数,该函数会阻止浏览器的默认操作,称为 防止默认。你的代码是:
Yep, it's a normal task. There's a function you can call on the event which the callback receives which prevents the browser's default action, called preventDefault. Your code would be: