gpt4 book ai didi

javascript - 使用 JavaScript 在 HTML 中查找和替换单词

转载 作者:太空宇宙 更新时间:2023-11-03 22:13:33 25 4
gpt4 key购买 nike

我有一些列出单词行的 HTML,每行附加到一个类。

我还有一个脚本函数,它会在 HTML 中对每次出现的单词“Five”进行全局查找和替换,并将其替换为单词“Zero”。

但是,问题是对于 class="second" 的每次出现,我只想将“五”替换为“零”。


问题

如何循环遍历 HTML 中的每一行,仅对特定类进行单词替换,例如使用 getElementsByClassName() 方法?


代码

单词替换示例 - https://jsfiddle.net/yb0sLhqp/

<html>
<body>

<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>

<button onclick="myFunction()">Replace</button>

<script>

function myFunction() {
document.body.innerHTML = document.body.innerHTML.replace(/Five/g, 'Zero');
}

</script>

</body>
</html>

最佳答案

所以用querySelectorAll选择所有元素,循环,替换文本。

function myFunction() {
document.querySelectorAll(".second") // select the elements
.forEach(elem => // loop over
elem.textContent = elem.textContent.replace(/Five/g, 'Zero') //replace the text
)
}

myFunction()

/* without the fat arrow
function myFunction() {
document.querySelectorAll(".second") // select the elements
.forEach(function(elem) { // loop over
elem.textContent = elem.textContent.replace(/Five/g, 'Zero') //replace the text
})
}
*/
<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>

<button onclick="myFunction()">Replace</button>

关于javascript - 使用 JavaScript 在 HTML 中查找和替换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com