javascript 从网址中删除主题标签(#)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23312006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:42:25  来源:igfitidea点击:

Remove hashtag(#) from url

javascriptjqueryhtmlurlhashtag

提问by Dchris

I want hash-tags to be removed from URL after they are used. For example, when i click on the link below:

我希望在使用后从 URL 中删除哈希标签。例如,当我点击下面的链接时:

<a href="#btnq1"><button type="button" name="" value="" id="btnq1">Just a button</button></a>

I want the hash-tag #btnq1 that appears to the URL of the page to be removed just after the action on this link happens. I tried the below jquery code with no success:

我希望在此链接上的操作发生后立即删除出现在页面 URL 中的哈希标签 #btnq1。我尝试了以下 jquery 代码但没有成功:

$('#btnq1').click(function(event){
   event.preventDefault();
   // your action
});

And even if this works, then how do i implement it to work for every hash tag that is added to the URL? I would like to solve it using javascript.

即使这有效,那么我如何实现它以适用于添加到 URL 的每个哈希标签?我想使用javascript解决它。

回答by A. Wolff

You could try that:

你可以试试:

$(window).on('hashchange', function(e){
    history.replaceState ("", document.title, e.originalEvent.oldURL);
});

回答by Honorable Chow

first add a class to your a tag that you want this behavior for, or a html 5 data- attribute. Then your link becomes;

首先将一个类添加到您想要此行为的标签或 html 5 数据属性。那么你的链接就变成了;

<a href="#btnq1" class="remove-hash"><button>Button</button></a>

$('body').on('click', ".remove-hash", function(e){
    $(this).removeAttr('href');
});