提问者:小点点

无法使用innerHTML方法更新另一个div元素中的div?


    <!DOCTYPE html>
<html>
<head>
    <title>Business Card</title>
    <script type="text/javascript">
        window.onload = init;
        function init(){
        var button = document.getElementById("populateFields");
        button.onclick = updateFields;
        }
        function updateFields(){
        document.getElementById("businessCard").innerHTML = "Business Card Info";
        document.getElementById("name").innerHTML = "Name";
        }
    </script>
</head>
<body>
<div id="businessCard">
<div id="name"></div>
</div>
<input type="button" value="populate fields" id="populateFields">
</body>
</html>

我可以看到id为'businessCard'的div更新为'businessCard Info',但我认为id为'name'的div没有更新。


共2个答案

匿名用户

外部div上的innerHTML清除内部div。保存内部div,然后在外部div上使用innerHTML

  window.onload = init;

  function init() {
    var button = document.getElementById("populateFields");
    button.onclick = updateFields;
  }

  function updateFields() {
    //save inner div
    var innerdiv = document.getElementById("name");
    innerdiv.innerHTML = "Name";

    var outerdiv = document.getElementById("businessCard");
    outerdiv.innerHTML = "Business Card Info";
    // add inner div back
    outerdiv.appendChild(innerdiv);

  }
<div id="businessCard">sme
  <div id="name">fdfdf</div>
</div>
<input type="button" value="populate fields" id="populateFields">

匿名用户

因为有人说innerHTML是邪恶的,因为它在DOM中的后果。另一个解决方案是使用。第一个孩子。节点值

window.onload = init;

function init() {
  var button = document.getElementById("populateFields");
  button.onclick = updateFields;
}

function updateFields() {
  document.getElementById("businessCard").firstChild.nodeValue = "Business Card Info";
  document.getElementById("name").firstChild.nodeValue = "Name";
}
<div id="businessCard">
  <div id="name"> </div>
</div>
<input type="button" value="populate fields" id="populateFields">