你錯就錯在使用querySelector,所以document.querySelector(".link").querySelector("a")
字面翻譯爲:獲得我的第.link
中的第一個a
;
使用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');
});
就像一個人站起來一樣,正則表達式看起來很奇怪不是嗎?可能是問題的一部分。你可以把這些代碼片段,以顯示他們的工作?第一個在技術上應該是'Array.prototype.forEach'而不是'[]'來防止實例化一個新的數組,但它並不重要。簡潔更清潔。 – TylerY86
您的示例在使用'.querySelectorAll(「。link a」);'時更具技術上的正確性,因爲它們將抓住後代中的錨點,而不僅僅是兒童。 – TylerY86
Vanilla版本的工作非常感謝 – Marksyw