繁体   English   中英

如何添加不仅仅是document.getElementById?

[英]How to add more than document.getElementById?

以下工作正常:

document.getElementById("comment").style.background=color

我想添加几个ID。 以下不起作用:

document.getElementById("comment, name, url").style.background=color
document.querySelectorAll("comment, name, url").style.background=color

有人可以建议什么代码避免编写新函数来绑定所有id吗?

编辑:这是我正在工作的代码:在头上我有:

<script>
function setbg(color)
{
document.getElementById("comment").style.background=color
}
</script>

它很好地样式了以下文本区域:

<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4" required="" title="Mandatory field" onfocus="this.value=''; setbg('#e5fff3');" onblur="setbg('white')" placeholder="Add a comment here..." style="background-color: white; background-position: initial initial; background-repeat: initial initial;"></textarea></p>

但我希望它也可以用于:

<input type="text" name="url" id="url" value="" size="22" tabindex="3" placeholder="WWW" onfocus="this.value=''; setbg('#e5fff3');" onblur="setbg('white')">

以及其他字段,例如电子邮件,姓名等。

创建和使用功能:

function colorElement(id, color){
    document.getElementById(id).style.backgroundColor = color;
}

colorElement('comment', 'red');
colorElement('name', 'green');
colorElement('url', 'blue');

JS小提琴演示

或者,您可以使用元素id的数组:

['comment', 'name', 'url'].forEach(function(a){
    document.getElementById(a).style.backgroundColor = 'red';
});

JS小提琴演示

或者,作为前一个的发展(它允许您设置不同的颜色):

[{
    "id": "comment",
    "color": "red"
}, {
    "id": "name",
    "color": "green"
}, {
    "id": "url",
    "color": "blue"
}].forEach(function (a) {
    document.getElementById(a.id).style.backgroundColor = a.color;
});

JS小提琴演示

既然您标记了jQuery,这是一种方法:

$("#comment, #name, #url").css("background-color",color);

这将获取多个id,并将样式应用于它们。

getElementById方法只能获取一个元素,因此您需要在每个id上使用它:

var ids = ["comment", "name", "url"];
for (i in ids) {
  document.getElementById(ids[i]).style.background = color;
}

querySelectorAll具有一个选择器,因此您需要在每个ID前面加上#前缀,然后需要遍历结果,因为您一次只能在一个元素上设置一个属性:

var el = document.querySelectorAll("#comment, #name, #url");
for (i in el) {
  el[i].style.background = color;
}

演示: http//jsfiddle.net/Guffa/B3J4a/

另一种方法是创建一个ID数组并遍历该数组

var els=["comment", "name", "url"];

while (els.length){
  document.getElementById(els.pop()).style.backgroundColor = color;
}

您可以使用元素名称数组进行迭代,例如

for(var i=0; i<3; i++) 
{
   document.getElementById(array[i]).style.background=color;
}

暂无
暂无

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

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