2 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
您在每次迭代中都將替換result為 original text。因此,您應(yīng)該將代碼更改為:
function getColoredEngSample(text) {
let result = text;
const keywords = ["have", "has", "been", "ing"];
keywords.forEach(key => {
result = result.replace(key, `<span class='bold-sample'>${key}</span>`);
});
return result;
}

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
問(wèn)題是您使用的變量text不會(huì)隨時(shí)間變化。每次循環(huán)開(kāi)始一輪時(shí),它都會(huì)使用來(lái)自參數(shù)的相同文本text。在循環(huán)的下一次運(yùn)行中,文本更改被寫(xiě)入結(jié)果但不再使用。所以 result 將只包含最后一次循環(huán)的結(jié)果。
const engSample = document.querySelector(".eng-sample");
engSample.innerHTML = getColoredEngSample("I have been walking");
function getColoredEngSample(text) {
let result = text;
const keywords = ["have", "has", "been", "ing"];
keywords.forEach(key => {
result = result.replace(key, `<span class='bold-sample'>${key}</span>`);
});
return result;
}
.bold-sample { color: #ff3c00; }
<p class="eng-sample"></p>
添加回答
舉報(bào)