JavaScript使用ID更改DIV背景

时间:2015-10-27 14:26:44

标签: javascript background

我有<div>它的ID =&#34; 123456&#34;

如果我运行以下内容,我会在console.log中显示123456

dId = obj.id,
console.log(dId);

如果我这样做,我可以改变背景

document.getElementById("123456").style.background="#EEE000";

然而,这失败了&#34; Uncaught TypeError:无法读取属性&#39; style&#39;为null &#34;

document.getElementById(dId).style.background="#EEE000";

如何使用var dId

执行此操作

更新 为清晰起见 obj =

<div id="123456" class="drag" style="border-style: solid; cursor: move;">TEST</div>

obj.id = 123456

更新 新工作JFiddle jsfiddle.net/pyefk58z/2当项目被拖动到放置区域时,如何更改该项目背景颜色以在放置列表中显示它?

由于

2 个答案:

答案 0 :(得分:1)

您可以将dID用作id,您应该检查dId是否包含正确的id

&#13;
&#13;
var obj = {
  id: 123456 // does not matter string or integer
};

var dId = obj.id;

document.getElementById(dId).style.background = "#EEE000";
&#13;
<div id="123456">
  Test
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

只需使用dId而不使用document.getElementById()

此外,您的ID名称无效CSS语法:http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier

https://jsfiddle.net/ryanpcmcquen/foLxrqrc/

&#13;
&#13;
var dId = document.querySelector('#a123456');
console.log(dId);
//document.getElementById("a123456").style.background = "#EEE000";
dId.style.background = "#EEE000";
&#13;
div {
  width: 100px;
  height: 100px;
}
&#13;
<div id="a123456"></div>
&#13;
&#13;
&#13;

鉴于您希望obj相等,这将起作用:

https://jsfiddle.net/ryanpcmcquen/ewct9kL3/

&#13;
&#13;
var obj = document.querySelector('#a123456');
var dId = obj.id;
console.log(dId);
//document.getElementById("a123456").style.background = "#EEE000";
document.getElementById(dId).style.background = "#EEE000";
&#13;
div {
  width: 100px;
  height: 100px;
}
&#13;
<div id="a123456" class="drag" style="border-style: solid; cursor: move;">TEST</div>
&#13;
&#13;
&#13;

我仍然建议使用我的第一种方式,但对每一种方式都是如此。