2016-03-23 37 views
0
<!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的div,'businessCard'更新爲「名片信息」,但是,我內部的ID爲'name'的div沒有更新。無法使用innerHTML方法更新另一個div元素中的div?

+3

一旦您設置businessCard.innerHTML =「名片信息」,即內部的div走了 – Wainage

+0

請問有什麼辦法..或者唯一的辦法是單獨div的? – tharun139

+0

您可以將內部div添加回外部div:http://stackoverflow.com/questions/14004117/create-div-and-append-div-dynamically –

回答

0

innerHTML在外部div清除你的內部股利。在外部div上使用innerHTML之前保存內部div。

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">

0

因爲有人說innerHTML是邪惡的,因爲它在DOM後果。另一種解決方案是使用.firstChild.nodeValue

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">