英文:
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 = ["something", "something2", "something3"];
for (let id of ids) document.getElementById(id).style.display = "block";
<!-- language: lang-html -->
<a id="something">Text</a>
<a id="something2">Text</a>
<a id="something3">Text</a>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论