在JavaScript中,是否有一种简短的代码来更改多个ID的CSS样式?

huangapple go评论81阅读模式
英文:

Is there any short code for the change of css style of multiple id's in JavaScript?

问题

可以考虑将上面的代码片段替换为类似以下的内容吗?(实际上我不知道格式是什么)

style.display=block for ids='fill2a','show2','choice2';

我可以创建一个数组然后进行操作吗?请友好地解释该怎么做。

英文:

Consider the set of codes I have for my three elements of ids fill2a, show2, choice2:

document.getElementById("fill2a").style.display="block"; 
document.getElementById("show2").style.display="block";
document.getElementById("choice2").style.display="block"; 

Can I replace the above code snippet into something like this? (I actually don't know the format)

style.display=block for ids='fill2a','show2','choice2';

Can I create an array and then work? Explain kindly what to do.

答案1

得分: 6

你可以尝试创建一个元素ID数组。然后遍历它们以设置样式,就像以下的方式:

const elementIdArr = ["fill2a", "show2", "choice2"];
elementIdArr.forEach(id => document.getElementById(id).style.display = "block");
英文:

You can try creating an array of element's id. Then iterate over them to set the style like the following way:

const elementIdArr = ["fill2a", "show2", "choice2"];
elementIdArr.forEach(id => document.getElementById(id).style.display = "block");

答案2

得分: 2

不要直接处理元素的样式。

使用类和后代组合器编写样式表:

.ancestor.active .fill,
.ancestor.active .show,
.ancestor.active .choice { display: block; }

然后在祖先元素上添加类:

document.getElementById('ancestor2').classList.add('active');
英文:

Don’t address the style of the elements directly.

Write a stylesheet using classes and descendant combinators:

.ancestor.active .fill,
.ancestor.active .show,
.ancestor.active .choice { display: block; }

Then add the class on the ancestor:

document.getElementById(‘#ancestor2).classList.add(active);

答案3

得分: 1

你可以使用 for... in 循环来遍历一个包含 ID 的数组:

var ids = ["something", "something2", "something3"];
for (let id of ids) document.getElementById(id).style.display = "block";
<a id="something">Text</a>
<a id="something2">Text</a>
<a id="something3">Text</a>
英文:

You could use a for... in loop to loop over an array of ID's:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var ids = [&quot;something&quot;, &quot;something2&quot;, &quot;something3&quot;];
for (let id of ids) document.getElementById(id).style.display = &quot;block&quot;;

<!-- language: lang-html -->

&lt;a id=&quot;something&quot;&gt;Text&lt;/a&gt;
&lt;a id=&quot;something2&quot;&gt;Text&lt;/a&gt;
&lt;a id=&quot;something3&quot;&gt;Text&lt;/a&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月11日 13:45:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658978.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定