我想让for循环的功能在按键或鼠标按下时一个一个执行
i want the function of for loop to perform one by one when a key or mouse is pressed
<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;
结果将是:
最广义的自然是物质世界或宇宙
我想要的:
当第一次触发任何键时:
最广义的自然是物理世界或宇宙
任意键第二次触发时:
广义上的自然是物理世界或宇宙
任意键第三次再次触发时:
最广义的自然是物理世界或宇宙
而不是 for
循环,我建议您使用 built-in 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>
<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;
结果将是: 最广义的自然是物质世界或宇宙
我想要的: 当第一次触发任何键时: 最广义的自然是物理世界或宇宙
任意键第二次触发时: 广义上的自然是物理世界或宇宙
任意键第三次再次触发时: 最广义的自然是物理世界或宇宙
而不是 for
循环,我建议您使用 built-in 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>