添加兄弟div

时间:2018-03-29 21:15:09

标签: javascript html css

当我将一个兄弟div添加到#boundary div时,我不能再改变#box子div的样式了。我究竟做错了什么?以下是我的代码的简化版本:

let box = document.getElementById("box");
let boundary = document.getElementById("boundary")

//Adding this line prevents my code from changing the #box style to blue
boundary.innerHTML += "<div>A</div>"

document.addEventListener("keydown", function(event) {
  if (event.key == "ArrowDown") {
    box.style.backgroundColor = "blue"
  }
})
#box {
  width: 75px;
  height: 75px;
  background-color: green;
  border: solid black 1px;
  position: absolute;
  top: 100px;
  left: 100px;
}
<div id="boundary">
  <div id="box"></div>
</div>

3 个答案:

答案 0 :(得分:2)

当您向innerHTML附加新字符串时,就像在#boudary内创建新的HTML内容一样,因此您选择的旧元素与创建的新元素不同。

要验证这一点,请在DOM更改后选择您的元素,然后您将创建新元素并且您将能够更改其样式:

&#13;
&#13;
let boundary = document.getElementById("boundary")

boundary.innerHTML += "<div>A</div>";

//Here you select the new one
let box = document.getElementById("box");

document.addEventListener("click", function(event) {

  box.style.backgroundColor = "blue"

})
&#13;
#box {
  width: 75px;
  height: 75px;
  background-color: green;
  border: solid black 1px;
  position: absolute;
  top: 100px;
  left: 100px;
}
&#13;
<div id="boundary">
  <div id="box"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

innerHTML添加字符串会创建一个新的#box DOM元素,这会破坏代码中的box引用。请改用Element.insertAdjacentHTML()

let box = document.getElementById("box");
let boundary = document.getElementById("boundary")

boundary.insertAdjacentHTML( 'beforeend', "<div>A</div>");

document.addEventListener("keydown", function(event) {
  if (event.key == "ArrowDown") {
    box.style.backgroundColor = "blue"
  }
})
#box {
  width: 75px;
  height: 75px;
  background-color: green;
  border: solid black 1px;
  position: absolute;
  top: 100px;
  left: 100px;
}
<div id="boundary">
  <div id="box"></div>
</div>

另一种选择是删除let box = document.getElementById("box");行。这将起作用,因为every element with id creates an automatic global variable引用它并自动更新。

let boundary = document.getElementById("boundary")

boundary.innerHTML += "<div>A</div>";

document.addEventListener("keydown", function(event) {
  if (event.key == "ArrowDown") {
    box.style.backgroundColor = "blue"
  }
})
#box {
  width: 75px;
  height: 75px;
  background-color: green;
  border: solid black 1px;
  position: absolute;
  top: 100px;
  left: 100px;
}
<div id="boundary">
  <div id="box"></div>
</div>

答案 2 :(得分:-1)

你需要在它后面加一个分号。

    boundary.innerHTML += "<div>A</div>";

我希望这会有所帮助。