简体   繁体   English

如何使用 JavaScript 更改多个 html 标签的文本内容?

[英]How to change text content of multiple html tags using JavaScript?

For example:例如:

<p> 1 </p>
<p> 2 </p>
<p> 3 </p>

As you can see that, there are 3 paragraph tag with the different number.如您所见,有3 个不同编号的段落标签 So, using JavaScript read the content of the p tag and changed the text according to the content received from the p tag.因此,使用 JavaScript 读取 p 标签的内容并根据从 p 标签接收到的内容更改文本。

Suppose, first p tag has content 1 so changed it into "active" .假设,第一个 p 标签的内容为1 ,因此将其更改为"active" Second p tag has content 2 so changed it into "deactivated" with that third tag contain 3 so changed it into "others" .第二个 p 标签的内容为2 ,因此将其更改为“已停用” ,而第三个标签包含3 ,因此将其更改为“其他”

Where output seems like:输出看起来像:

<p> Active </p>
<p> Deactivated </p>
<p> Others </p>

Even if we changed the p tag order to this:即使我们将 p 标记顺序更改为:

<p> 2 </p>
<p> 3 </p>
<p> 1 </p>

the output must be:输出必须是:

<p> Deactivated </p>
<p> Others </p>
<p> Active </p>

Use an array with the values you need, for each paragraph convert the original textValue to a number and retrieve the value from the array using that number.使用具有所需值的数组,对于每个段落,将原始 textValue 转换为数字,并使用该数字从数组中检索值。

Or use some kind of templating .或者使用某种 模板

 const values = [`Active`, `Deactivated`, `Others`]; document.querySelectorAll(`p`).forEach( (p) => p.textContent = values[+(p.textContent.trim()) - 1]);
 <p> 1 </p> <p> 3 </p> <p> 2 </p> <p> 3 </p> <p> 1 </p> <p> 2 </p>

You can use switch and .innerText您可以使用switch.innerText

 const pEles = [...document.querySelectorAll("p")]; pEles.forEach(ele => { switch (ele.innerText) { case "1": ele.innerText = "Active" break; case "2": ele.innerText = "Deactivated" break; case "3": ele.innerText = "Others"; break; } })
 <p>1</p> <p>2</p> <p>3</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM