我真的遇到了这个replaceChild()函数的问题。我正在尝试自学javascript。感谢上帝,我从java学习了面向对象的基础知识,否则我将完全迷失。可以这段代码应该用另一张图片替换一张图片。它根本没有取代图片。有人能告诉我我做错了什么吗?我真的很感激。
<html>
<body>
<script type = "text/javascript">
function isImage(y){
// used to embed images
var peter = document.createElement("img");
peter.width = y;
peter.height = "600";
peter.src = "site.jpg";
document.body.appendChild(peter);
}
function secondImage(x){
var peterII = document.createElement("img");
peterII.width = x;
peterII.height = "600";
peterII.src = "home.png";
document.body.replaceChild(peterII,peter);
}
//function listener
function addListeners1(){
// adds eventlistener to the button listed at the bottom
document.getElementById('mybutton').addEventListener("click",btntwo);
document.getElementById('mybuttonII').addEventListener("click",btnthree);
}
function btntwo(){
isImage(400);
}
function btnthree(){
secondImage(400);
}
// adds listener when the window is loaded
onload = addListeners1;
//onload = isImage(400);
</script>
<! adds buttons>
<button id="mybutton" style="width:100;height:50" value = "clickhere">MyButton</button>
<button id="mybuttonII" style="width:100;height:50">MyButtonII</button>
</body>
</html>
答案 0 :(得分:0)
检查此代码
var peter;
function isImage(y){
// used to embed images
peter = document.createElement("img");
peter.width = y;
peter.height = "600";
peter.src = "http://www.gettyimages.com/CMS/Pages/ImageCollection/StaticContent/image5_170127819.jpg";
document.body.appendChild(peter);
}
function secondImage(x){
var peterII = document.createElement("img");
peterII.width = x;
peterII.height = "600";
peterII.src = "http://www.studiotv.com.au/wp-content/uploads/2014/07/Klimas-website-edited.jpg";
document.body.replaceChild(peterII,peter);
}
//function listener
function addListeners1(){
// adds eventlistener to the button listed at the bottom
document.getElementById('mybutton').addEventListener("click",btntwo);
document.getElementById('mybuttonII').addEventListener("click",btnthree);
}
function btntwo(){
isImage(400);
}
function btnthree(){
secondImage(400);
}
addListeners1();
<! adds buttons>
<button id="mybutton" style="width:100;height:50" value = "clickhere">MyButton</button>
<button id="mybuttonII" style="width:100;height:50">MyButtonII</button>