【发布时间】:2013-07-04 21:26:19
【问题描述】:
我需要更改链接的href,这样最后就不会说.com,而是说.net。
$('selector').attr('href','http://example.com');
这是我目前正在使用的代码,但它只是替换了整个属性。我只希望它改变.com。
有人可以修复我的代码以使其正常工作吗?我知道这是非常基础的,但我是 jQuery 的初学者。
【问题讨论】:
标签: jquery attributes href
我需要更改链接的href,这样最后就不会说.com,而是说.net。
$('selector').attr('href','http://example.com');
这是我目前正在使用的代码,但它只是替换了整个属性。我只希望它改变.com。
有人可以修复我的代码以使其正常工作吗?我知道这是非常基础的,但我是 jQuery 的初学者。
【问题讨论】:
标签: jquery attributes href
可以使用attr的回调函数:
$('selector').attr('href', function(_, href) {
return href.replace('.com', '.net');
});
【讨论】:
试试这个:
var a = $('selector');
a.attr('href', a.attr('href').replace('.com', '.net'));
【讨论】: