jQuery 如何用 each 替换元素的 attr href ?// 去除网址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11369182/
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-08-26 10:32:24  来源:igfitidea点击:

How to replace element's attr href with each ? // strip url

jqueryhrefeachattr

提问by Barlas Apaydin

im trying to change href with each method,

我试图用每种方法更改 href,

here is demo, inspect a, you'll see there is no change

这是演示,检查一个,你会看到没有变化

html:

html:

<a href="#/news">News</a>
<a href="#/news/detail">Detail</a>
<a href="#/sport">Sport</a>
<a href="#/sport/football">Football</a>????????????

jQuery:

jQuery:

$('a').each(function() {
  $(this).attr('href').replace('#/',''); //tried to erase #/ from all hrefs
});?

回答by JaredPar

The code you posted will get the value as a stringthen properly replacethe values but it immediately discards the result. You need to pass in the replaced value to attr. Try the following

您发布的代码将获取值作为string然后正确replace的值,但它会立即丢弃结果。您需要将替换的值传递给attr. 尝试以下

$('a').each(function() {
  var value = $(this).attr('href');
  $(this).attr('href', value.replace('#/',''));
});?

回答by elclanrs

var href = $(this).attr('href');
$(this).attr('href', href.replace('#/',''));

回答by Shafiqul Islam

You can also check href value and make condition

您还可以检查 href 值并制作条件

<script type="text/javascript">
$('a').each(function() {
    var value = $(this).attr('href');
    if(value=='http://google.com')
    {
        $(this).attr('href', 'http://youtube.com');
    }
});?
</script>