从href锚中删除最后一个正斜杠 [英] Remove last forward slash from href anchor
问题描述
我有以下主播情况:
<a href="https://example.com/my-account/#example/" class="anchor">...</a>
由于#
链接的斜线,上述锚点给了我jQuery冲突.因为这是PHP生成的,所以我正在寻找一种 jQuery Javascript解决方案来删除该锚点href
的最后一个字符.我该怎么办?
The above anchor gives me a jQuery conflict because of the slash of the #
link. Because this is PHP generated I am looking for a jQuery Javascript solution to remove the last character of the href
of this anchor. How do I do that?
此jquery冲突的原因是,因为我网站上的#-链接是并且应该是滚动到ID的属性.因此它滚动到id元素.这是一项功能,我无法更改其构建方式,因此,我看到的唯一解决方案是从锚点中删除最后一个/
.
The reason for this jquery conflict is, because #-links on my site are and should be scroll-to-id properties. So it scrolls to the id-element. This is a functionallity I cannot change how it's build, so the only solution I see is to remove the last /
from the anchor.
推荐答案
由于#-link的斜线,上面的锚点给了我jQuery冲突
The above anchor gives me a jQuery conflict because of the slash of the #-link
我建议您应解决该冲突,因为在URL片段中包含/
并没有本质上的错误.如果这给您带来了错误,那么您需要更正您的逻辑.
I'd suggest that you should fix that conflict as there is nothing inherently wrong with having a /
in the fragment of the URL. If it's causing an error for you, then you need to fix your logic.
话虽这么说,可以通过将函数传递给prop()
来执行所需的操作,该函数使用正则表达式删除所有尾随的斜杠:
That being said, it's possible to do what you require by passing a function to prop()
which removes any trailing slashes using a regex:
$('.anchor').prop('href', function(i, href) {
return href.replace(/\/$/, '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<a href="https://example.com/my-account/#example/" class="anchor">...</a>
这篇关于从href锚中删除最后一个正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!