gpt4 book ai didi

javascript - 如何在循环中创建一个元素并将它(一个一个地添加 5 次)到特定的 div?

转载 作者:行者123 更新时间:2023-11-30 09:48:26 24 4
gpt4 key购买 nike

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 仍然是“空的”

最佳答案

试试这段代码

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

关于javascript - 如何在循环中创建一个元素并将它(一个一个地添加 5 次)到特定的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37739897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com