[英]Hide # in URL when clicking <a href=“#”>
I have the following code: 我有以下代码:
<p>
<a href="#" id="sobo-einblenden">einblenden</a>
<a href="#" id="sobo-ausblenden">ausblenden</a>
</p>
<div id="sozialbookmarks">
<p>
<b>Bereich für social bookmarks</b><br>
Hier kommen nun die üblichen Verdächtigen und Logos dazu.<br>
Nicht vergessen, meine Seite zu bookmarken!
</p>
</div>
<div id="sozialbookmarks2">
<p>
<b>Bereich für social bookmarks</b><br>
Hier kommen nun die üblichen Verdächtigen und Logos dazu.<br>
Nicht vergessen, meine Seite zu bookmarken!
</p>
</div>
When I click on <a href="#" id="sobo-einblenden">einblenden</a>
in the browser I will see: site.php#
. 当我在浏览器中单击
<a href="#" id="sobo-einblenden">einblenden</a>
时,我将看到: site.php#
。 How can I make it so that the #
is not added to the URL? 如何使
#
不会添加到URL中?
Use event.preventDefault() 使用event.preventDefault()
$('a').click(function(event){
event.preventDefault();
});
As noted in Dhara Parmar's answer , you can use a simple jQuery event listener on all the <a>
elements to prevent the default action (going to the hash) when clicked. 如Dhara Parmar的回答所述 ,您可以在所有
<a>
元素上使用简单的jQuery事件侦听器,以防止单击时执行默认操作(进入哈希)。
Here's a way to accomplish the same thing with vanilla JavaScript: 这是使用香草JavaScript完成相同操作的一种方法:
// all anchors
var elements = document.getElementsByTagName("a");
for (var i = 0; i < elements.length; i++) {
// attach event to each anchor tag
elements[i].addEventListener("click", function(event) {
// prevent default action when clicked
event.preventDefault();
});
}
There's a similar question regarding how to preventDefault()
with vanilla JavaScript that can be found here. 关于如何使用vanilla JavaScript防止
preventDefault()
有一个类似的问题,可以在这里找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.