gpt4 book ai didi

JavaScript 错误消息 : Uncaught TypeError: Cannot set property 'onclick' of null

转载 作者:行者123 更新时间:2023-12-02 17:33:58 26 4
gpt4 key购买 nike

下面的 JavaScript 代码没有显示任何内容,尽管该代码在 Fiddle 中完美运行。 javascript控制台给了我2条我不明白的错误消息:无法加载资源:net::ERR_FILE_NOT_FOUND和Uncaught TypeError: Cannot set property 'onclick' of null,所以任何人都理解错误消息的原因以及我该如何做让我的代码正常工作,以便它能够计算并显示用户将选择的内容?

代码是:

var numericalValues = new Array();
numericalValues["Alot"]= 4;
numericalValues["NotMuch"]= 2;
numericalValues["NoSometimes"]= 3;
numericalValues["Hate"]= 0;
numericalValues["Chocolate"]= 4;
numericalValues["Carrot"]= 0;
numericalValues["Both"]= 2;
numericalValues["None"]= 0;


function getScoreChoco()
{
var scoreChoco = 0;
var form = document.forms["form"];
var choco = form.elements["choco"];
for(var i=0; i<choco.length; i++)
{
if(choco[i].checked)
{
scoreChoco = numericalValues[choco[i].value];
break;
}

}
return scoreChoco;
}

function getScoreCake()
{
var scoreCake = 0;
var form = document.forms["form"];
var cake = form.elements["cake"];

for(var i=0; i<cake.length; i++)
{
if(cake[i].checked)
{
scoreCake = numericalValues[cake[i].value];
break;
}

}
return scoreCake;
}


function getTotal()
{

var totalScore = getScoreCake() + getScoreChoco();


document.getElementById('result').innerHTML = "Your total score is: "+totalScore;



document.getElementById('calculate').onclick=getTotal;
}

好的 HTML 代码:

<form id="form" name="form">
<fieldset id="controls">
<p>Do you like chocolate?
<label>Yes a lot </label>
<input type="radio" name="choco" id="alot" value="Alot" checked="true">

<label>Not that much </label>
<input type="radio" name="choco" id="notMuch" value="NotMuch">
<label>No, but still I don't mind eating it sometimes </label>
<input type="radio" name="choco" id="noSometimes" value="NoSometimes">

<label>No, I hate it </label>
<input type="radio" name="choco" id="hate" value="Hate">
</p>
<p>Do you prefer chocolate cake or carrot cake?
<label>chocolate </label>
<input type="radio" name="cake" id="chocolate" value="Chocolate" checked="true">

<label>Carrot </label>
<input type="radio" name="cake" id="carrot" value="Carrot">

<label>Both</label>
<input type="radio" name="cake" id="both" value="Both">

<label>None </label>
<input type="radio" name="cake" id="none" value="None">
</p>

<p>
<input type="button" name="Calculate" id="calculate" value="Calculate" />
</p>
<p id="result"></p>

</form>

最佳答案

我猜测您的 javascript 代码位于 HTML 代码之上。因此,当你尝试访问 document.getElementById('calculate') 时,html 代码还没有被解析,因此还没有 id 为 calculate 的元素,所以它返回未定义。尝试将 javascript 代码放在 body 标记的末尾,而不是放在任何位置(我猜可能是在 head 标记中)

关于JavaScript 错误消息 : Uncaught TypeError: Cannot set property 'onclick' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798177/

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