我正在尝试替换多个链接,但只替换了第一个链接, 其他所有保持不变。
function rep(){
var text = document.querySelector(".link").querySelector("a").href;
var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
document.querySelector(".link").querySelector("a").href = newText;
}
有什么建议吗?
我正在谈论的 .link
元素内有多个 a href
链接。
最佳答案
你的错误在于使用querySelector,所以document.querySelector(".link").querySelector("a")
字面意思是:给我第一个a
在第一个 .link
内;
使用querySelectorAll;您可以组合这两个选择器:
普通 JS:
[].forEach.call(document.querySelectorAll('.link a'), function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
或者,由于您会更频繁地选择项目,因此需要一些实用程序:
function $$(selector, ctx){
return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}
$$('.link a').forEach(function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})
或者在 jQuery 中:
$('.link a').each(function(){
this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
关于javascript - 替换多个链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39735452/