I want the user to be alerted and have to input a number. The corresponding number of images will appear. I have this code:
<!DOCTYPE hmtl>
<html>
<head>
<script>
//creating my function
function howMany(){
var numBurgers = parseInt(prompt('How many burgers do you want?', "3"));
var x = "";
for(var count = 0; count < numBurgers; count++;){
x += "<img src=\"burger.jpg\" />";
}
document.getElementById('burgerImages').innerHTML = x;
}
</script>
</head>
<body onload="howMany();">
<div id="burgerImages"></div>
</body>
</html>
Someone suggested that I replace "document.getElementById('burgerImages').innerHTML = x;" with "document.getElementById('burgerImages').appendChild(x)." but that does not work. Any ideas?
答案 0 :(得分:1)
Basically because appendChild
expect the parameter to be a Node Element
not a string.
You need to create different nodes, and then append those nodes :
var fragmentCollection = document.createDocumentFragment();
for (var i = 0; i < numBurgers; i++) {
var img = document.createElement("img");
img.setAttribute('src', 'burger.jpg');
fragmentCollection.appendChild(img);
}
var burgerContainer = document.getElementById('burgerImages');
burgerContainer.appendChild(fragmentCollection);
References: