gpt4 book ai didi

javascript - 无法读取 null 的属性 'setAttribute' - Javascript

转载 作者:行者123 更新时间:2023-11-30 19:53:37 28 4
gpt4 key购买 nike

我在这里看到了几个关于此错误的问题,并且在看到一些答案后我注意到普遍的共识是它是由于尚未创建 DOM 而引起的。我尝试了几种不同的解决方案来修复它,例如将我的脚本移动到标签之前,在创建图像之前和之后使用日志输出以确保实际上正确创建了对象,但没有解决我的问题。我是 Javascript 的新手,所以我可能明显遗漏了什么?

var dice = [6, 6, 6, 6, 6];

function rollDice() {
for (var i = 0; i < dice.length; ++i) {
var num = Math.floor(Math.random() * 6 + 1);
dice[i] = 1;
document.write(dice[i] + "<br>");
}
for (var i = 0; i < dice.length; ++i) {
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value];
}
document.getElementById("dice_1").setAttribute("src", path)
}
<html>

<head>

<meta charset="utf-8">
<title>Project 1</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
<h1> This is a javascript application</h1>
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<div>
<img id="dice_1" src="images/dice 1.png">
<img id="dice_2" src="images/dice 1.png">
<img id="dice_3" src="images/dice 1.png">
<img id="dice_4" src="images/dice 1.png">
<img id="dice_5" src="images/dice 1.png">
</div>
<input id="but" type="button" onclick="rollDice()" value="Roll Dice.">
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<script type="text/javascript" src="scripts/script.js"></script>
</body>

</html>

最佳答案

由于您在文档加载后使用 document.write,它会清除整个文档(由于调用了 document.open())。因此,您的 img 元素不存在,无法针对它们运行 setAttribute。请尝试以下操作(请注意由于数组索引从零开始而需要进行的索引更正):

var dice = [6,6,6,6,6];
var results;
var resultsContainer = document.querySelector('.results');

function rollDice(){
// clear results array
results = [];
for(var i =0; i<dice.length; ++i){
var num = Math.floor(Math.random()*6 +1);
dice[i] = num;
results.push(dice[i]);
}
for(var i =0; i< dice.length; ++i){
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3.png", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value - 1];
document.getElementById("dice_"+ (i + 1)).setAttribute("src",path);
}
// convert results array to text with <br> between them
var resultsStr = results.join("<br>");
// display results as text to page
resultsContainer.innerHTML = resultsStr;
}

关于javascript - 无法读取 null 的属性 'setAttribute' - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54240953/

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