<div id="text">Nature in the broadest sense is the physical world or universe</div>
let el = document.getElementById(text);
let eltext = el.innerText;
let final = eltext.split(" ");
let i;
for (i = 0; i < final.length; i ) {
if (final[i] === "the") {
final[i] = `<b>${final[i]}</b>`;
}
let result = (final " ").replace(/,/g, " ");
el.innerHTML = result;
結果將是:最廣義的自然是物理 世界或宇宙
我想要什么: 當第一次觸發任何鍵時:最廣義的自然是物理世界或宇宙
第二次觸發任意鍵時:最廣義的自然是物理世界或宇宙
第三次觸發任意鍵時:最廣義的自然是物理世界或宇宙
uj5u.com熱心網友回復:
for我建議您使用內置方法而不是回圈,Array以提高可讀性。在這里,我擴展了您的示例句子,以展示它如何適應具有更多目標詞的更長句子。
const text = document.querySelector('#text').innerText.split(' ');
const indices = text.map((word, index) => word === 'the' ? index : 0)
.filter(i => i !== 0);
let highlightIndex = 0;
function toggle() {
const arr = [...text];
arr[indices[highlightIndex]] = `<strong style="color: red;">${arr[indices[highlightIndex]]}</strong>`;
document.querySelector('#text').innerHTML = arr.join(' ');
highlightIndex = 1;
if (highlightIndex > indices.length -1 ) highlightIndex = 0;
}
window.addEventListener('keydown', toggle);
window.addEventListener('click', toggle);
<div id="text">Nature in the broadest sense is the physical world or universe. Introduce the article here for testing the code.</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429106.html
標籤:javascript html for循环
上一篇:MYSQLSelectQuery非常快,但是從這個select中創建臨時表太慢了
下一篇:c語言編程輸出中的求和實作不正確
