简体   繁体   中英

Replacing a substring in href-attribute using jQuery

I have some "a" tags in div. I have to change part of the href. For example: http://jsfiddle.net/A6z88/ , I have to change only 'foo' in the href with 'asd'. Thanks a lot and sorry for my english :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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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