2016-03-15 29 views
-2

此代碼中的錯誤在哪裏?在div錯誤中的Javascript圖像

<!DOCTYPE html> 
<html> 
<body> 
<div id="img"></div> 

<button onclick="myFunction()">Try it</button> 

<script> 
function myFunction() { 
    var img = document.getElementById("img"); 
    var x = document.createElement("IMG"); 
    x.setAttribute("src", "img_pulpit.jpg"); 
    x.setAttribute("width", "304"); 
    x.setAttribute("width", "228"); 
    x.setAttribute("alt", "The Pulpit Rock"); 
    document.img.appendChild(x); 
} 
</script> 

</body> 
</html> 

我把ID從DIV,但圖像沒有加載在這個div ..

我不知道哪裏是錯誤。

在此先感謝

+0

你設置'width'屬性的兩倍。還要確保文件'img_pullit.jpg'與你的html文件在同一個文件夾中,並在調用appendChild'函數時移除'document.'部分。 –

+0

而不是document.img.appendChild(x);使用img.appendChild(x) – blessenm

+0

在瀏覽器開發人員工具中打開控制檯窗口,您將清楚地看到問題出在哪裏。 –

回答

0

您需要將script標記放置在html之前。
使用img.appendChild(x);代替document.img.appendChild(x);

<script> 
 
    function myFunction() { 
 
     var img = document.getElementById("img"); 
 
     var x = document.createElement("IMG"); 
 
     x.setAttribute("src", "img_pulpit.jpg"); 
 
     x.setAttribute("width", "304"); 
 
     x.setAttribute("width", "228"); 
 
     x.setAttribute("alt", "The Pulpit Rock"); 
 
     img.appendChild(x); 
 
    } 
 

 
</script> 
 
<div id="img"></div> 
 
<button onclick="myFunction()">Try it</button>

0

錯誤就出在這裏document.img.appendChild(x);

將其更改爲img.appendChild(x);

<!DOCTYPE html> 
 
<html> 
 
<body> 
 
<div id="img"></div> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<script> 
 
function myFunction() { 
 
    var img = document.getElementById("img"); 
 
    var x = document.createElement("IMG"); 
 
    x.setAttribute("src", "img_pulpit.jpg"); 
 
    x.setAttribute("width", "304"); 
 
    x.setAttribute("height", "228"); //change width to height 
 
    x.setAttribute("alt", "The Pulpit Rock"); 
 
    img.appendChild(x); 
 
} 
 
</script> 
 

 
</body> 
 
</html>

此外,你設置width屬性的兩倍。將其更改爲height