如何在循环中创建一个元素并将其附加到特定的 div(5 次,一个接一个)?
how to create an element in a loop and append it (5 times one by one) to the particular div?
我m trying to create an element(image) and then set a loop that would produce 5 images in one div(its id="leftSide"). Here
我的代码:
<script>
var number_of_faces = 0;
var theLeftSide = document.getElementById("leftSide");
function generate_faces() {
for (number_of_faces = 0; number_of_faces < 6; number_of_faces++) {
newFace = document.createElement("img");
newFace.setAttribute(
"src",
"http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png"
);
document.getElementById("leftSide").appendChild("img");
}
}
</script>
body onload 必须调用该函数,但没有任何反应。 Div 仍然是 "empty"
将 document.getElementById("leftSide").appendChild("img");
更改为 document.getElementById("leftSide").appendChild(newFace);
您传递了字符串 "img" 而不是 newFace 元素。
使用 document.getElementById("leftSide").appendChild(newFace);
并且循环应该是 < 5
循环 5 次。
试试这个代码
<!DOCTYPE html>
<html>
<head>
<title>Blah</title>
</head>
<body>
<div id="leftSide">
</div>
<script>
var number_of_faces = 0;
var theLeftSide = document.getElementById("leftSide");
function generate_faces() {
for (number_of_faces = 0; number_of_faces < 5; number_of_faces++) {
newFace = document.createElement("img");
newFace.setAttribute(
"src",
"http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png"
);
theLeftSide.appendChild(newFace);
}
}
generate_faces();
</script>
</body>
</html>
我m trying to create an element(image) and then set a loop that would produce 5 images in one div(its id="leftSide"). Here
我的代码:
<script>
var number_of_faces = 0;
var theLeftSide = document.getElementById("leftSide");
function generate_faces() {
for (number_of_faces = 0; number_of_faces < 6; number_of_faces++) {
newFace = document.createElement("img");
newFace.setAttribute(
"src",
"http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png"
);
document.getElementById("leftSide").appendChild("img");
}
}
</script>
body onload 必须调用该函数,但没有任何反应。 Div 仍然是 "empty"
将 document.getElementById("leftSide").appendChild("img");
更改为 document.getElementById("leftSide").appendChild(newFace);
您传递了字符串 "img" 而不是 newFace 元素。
使用 document.getElementById("leftSide").appendChild(newFace);
并且循环应该是 < 5
循环 5 次。
试试这个代码
<!DOCTYPE html>
<html>
<head>
<title>Blah</title>
</head>
<body>
<div id="leftSide">
</div>
<script>
var number_of_faces = 0;
var theLeftSide = document.getElementById("leftSide");
function generate_faces() {
for (number_of_faces = 0; number_of_faces < 5; number_of_faces++) {
newFace = document.createElement("img");
newFace.setAttribute(
"src",
"http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png"
);
theLeftSide.appendChild(newFace);
}
}
generate_faces();
</script>
</body>
</html>