我页面上有一个链接,如下:
<li class="jump"><a href="http://example.com/#about">About Me</a></li>
我想使用jQuery删除.jump类中任何URL的'http://example.com/'部分。你能告诉我正确的方向并提供最简单的代码吗?我希望代码删除井号前面的任何内容,而无需指定URL(例如,在可能的情况下在jQuery代码中删除http://example.com/)。谢谢!
我页面上有一个链接,如下:
<li class="jump"><a href="http://example.com/#about">About Me</a></li>
1) 使用.each()
遍历所有锚点
2) 将当前href按#
分割,并使用第二个数组元素
3) 将新的href与前面的#
连接起来,并设置为新的href
$('.jump a').each(function(){
$(this).attr('href','#'+$(this).attr('href').split('#')[1]);
});
#
作为分隔符来拆分URL:var url = $(".jump").attr("href"); // "http://example.com/#about"
var split_url = url.split("#");
var after_hash = split_url[1];
你的after_hash
变量现在应该包含值:"about"。如果你打算将它插入回href
属性中,你需要重新添加锚字符到这个值中。
由于我听起来像是你打算在多个URL上使用这个功能,我建议将这段代码放入一个函数中,并在需要时调用。
substring
和 lastIndexOf
。$(".jump a").each(function() {
var $this = $(this),
href = $this.attr("href");
$this.attr("href", href.substring(href.indexOf("#")));
});
#
字符始终是片段标识符。如果有多个#
(例如/abc#one#more
),使用lastIndexOf
可能会找到错误的#
。 - Sverri M. Olsen以下是我使用jQuery的方法:
$(".jump a").each(function() {
var newHref = $(this).attr("href").replace("http://example.com/", "");
$(this).attr("href", newHref);
});
.indexOf()
和.slice()
方法,或使用.split()
方法。你没有投入太多努力,是吗? - Sverri M. Olsen