[英]For event.target in onclick - "Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')"
I'm trying to have my html call a javascript function onclick in which the function itself references the event that called it, but I keep getting this error:我试图让我的 html 调用 8822996504788 function onclick,其中 function 本身引用调用它的事件,但我不断收到此错误:
Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')
at play (c:\Users\C2Ran\Desktop\Practice\app.js:5:16)
at onclick (c:\Users\C2Ran\Desktop\Practice\index.html:24:68)
Here's my html:这是我的 html:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="app.js" defer></script>
</head>
<body>
<input type="button" value="X" id="turn" onclick="play(this);">
</body>
</html>
Here's my javascript:这是我的 javascript:
var turn = "X"
function play(event) {
var cell = event.target;
cell.value = turn;
console.log(turn);
if(turn == "X")
{
turn = "O"
}
else
{
turn = "X"
}
}
Is there something I'm missing?有什么我想念的吗? Why is it saying value
is undefined?为什么说value
未定义? Is it not getting the event correctly?是不是没有正确获取事件? Or does onclick not count as an event?或者 onclick 不算事件? I also tried event.currentTarget
instead我也试过event.currentTarget
Avoid using function calling in HTML attributes, instead use addEventListener
,避免使用 function 调用 HTML 属性,而是使用addEventListener
,
Your problem is that you are using this
when you should be using event.currentTarget
你的问题是你在应该使用event.currentTarget
this
时候使用它
Note: I've improved a bit your code in play()
function注意:我在play()
function 中改进了你的代码
function play(cell) { cell.value = cell.value === "X"? "O": "X" console.log(cell.value); } document.getElementById('turn').addEventListener('click', e => play(e.currentTarget))
<input type="button" value="X" id="turn">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.