[英]jQuery Adds Extra '#' to URL?
I noticed sometimes that when I use jQuery, a extra '#' gets added to the end of my URL after a jQuery function is called. 我有时注意到,当我使用jQuery时,在调用jQuery函数后,URL的末尾会添加一个额外的“#”。 For example, the URL 'www.mywebsite.com' will change to 'www.mywebsite.com/#' once a jQuery function is initialized. 例如,初始化jQuery函数后,URL“ www.mywebsite.com”将更改为“ www.mywebsite.com/#”。 The same for 'www.testsite.com/users.php', is changed to 'www.testsite.com/users.php#'. “ www.testsite.com/users.php”的内容已更改为“ www.testsite.com/users.php#”。
Why does jQuery add the '#'? jQuery为什么要添加“#”?
If your function is running from a link onclick, you need to use event.preventDefault() 如果您的函数是通过onclick链接运行的,则需要使用event.preventDefault()
See http://api.jquery.com/event.preventDefault/ 参见http://api.jquery.com/event.preventDefault/
Usually this is because you have a dummy link with a jQuery click handler. 通常这是因为您有一个带有jQuery click处理程序的虚拟链接。 It's common to see links with an href of #
that are only used to trigger some JavaScript. 通常会看到带有href #
链接仅用于触发一些JavaScript。
<a href="#" class="button">Go</a>
Resolve this easily by making a habit of calling e.preventDefault()
in your click handlers: 通过习惯在点击处理程序中调用e.preventDefault()
来轻松解决此问题:
$(function() {
$(".button").click(function(e) {
e.preventDefault();
...
});
});
You can also use return false
, but that has the added effect of stopping event propagation. 您还可以使用return false
,但这具有停止事件传播的附加效果。 I like to add e.stopPropagation()
explicitly if I also want that effect. 我也想显式地添加e.stopPropagation()
。 It makes the code and it's intended effect more explicit and clear for future developers (or myself in 6 months). 它使代码及其预期效果对于未来的开发人员(或我自己在6个月内)更加明确和清晰。
Probably you're getting this when handling a click event. 处理点击事件时可能会收到此消息。 If you don't want that happens, just add event.preventDefault()
or return false
at the end in event handler function. 如果您不希望发生这种情况,只需添加event.preventDefault()
或在事件处理函数的末尾return false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.