我目前正在尝试排除以下代码的故障:
function getStuff(){
document.querySelector('#tuna').onclick=scorefunc;
}
function scorefunc() {
var scorep;
scorep = scorep + 1;
document.getElementById("scorez").innerHTML = "You have found me: " + scorep + " times";
}基本上,当用户单击id为金枪鱼的段落元素(p)时,会运行scorefunc。我试图在每次点击的时候将分数加1,但结果却显示"You have found me NaN times“
如果这是错误的地方,我的HTML代码看起来是这样的:
<p id ="scorez">You have found me: </p>提前感谢:)
发布于 2020-02-10 11:52:44
问题是scorep是undefined。您声明了它(即var scorep),但您从未定义过它,所以您实际上是在尝试将undefined和1添加在一起,这当然会产生NaN。
将您的声明更改为var scorep = 0以解决此问题。
此外,如果希望每次单击p元素时scorep都递增1,则必须创建一个closure或在本地范围外声明变量。
var scorep = 0
function scorefunc() {
scorep += 1
document.getElementById("scorez").innerHTML = `You have found me: ${scorep} times`
}https://stackoverflow.com/questions/60142387
复制相似问题