简体   繁体   English

使用jQuery替换href属性中的子字符串

[英]Replacing a substring in href-attribute using jQuery

I have some "a" tags in div. 我在div中有一些“ a”标签。 I have to change part of the href. 我必须更改href的一部分。 For example: http://jsfiddle.net/A6z88/ , I have to change only 'foo' in the href with 'asd'. 例如: http : //jsfiddle.net/A6z88/ ,我只需要在href中用'asd'更改'foo'。 Thanks a lot and sorry for my english :D 非常感谢,对不起我的英语:D

$('div a').each(function(){
   $(this).attr('href', $(this).attr('href').replace('foo', 'asd'));
});

I'd do 我会做

$('#links a').each(function(){
   this.href = this.href.replace('/foo/', '/asd/'); 
});

请参阅: http//jsfiddle.net/A6z88/3/

The most elegant way with the fewest function calls is: 函数调用最少的最优雅的方式是:

$('a').attr('href', function(i, val){
  return val.replace('foo', 'asd');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM