我的html:
<!doctype hmtl>
<html>
<head>
</head>
<body>
<script type='text/javascript'>
var playerId = 1;
function event(action) {
let req = new XMLHttpRequest('/act?id='+String(playerId)+'&action='+action);
alert(action);
}
</script>
<img src="up.png" width='100' height='100' onclick='event("up");'>
<img src="down.png" width='100' height='100' onclick='event("down");'>
<img src="left.png" width='100' height='100' onclick='event("left");'>
<img src="right.png" width='100' height='100' onclick='event("right");'>
<img src="fire.png" width='100' height='100' onclick='event("fire");'>
</body>
</html>
我确信该图像是可点击的。但为什么错误消息显示event is not a function
?我需要帮助。
最佳答案
这样,您将尝试访问全局对象window.event
,因此只需重命名您的函数即可。
您自己的代码,将函数 event
重命名为 test
:
<!doctype hmtl>
<html>
<head>
</head>
<body>
<script type='text/javascript'>
var playerId = 1;
function test(action) {
let req = new XMLHttpRequest('/act?id='+String(playerId)+'&action='+action);
alert(action);
}
</script>
<img src="up.png" width='100' height='100' onclick='test("up");'>
<img src="down.png" width='100' height='100' onclick='test("down");'>
<img src="left.png" width='100' height='100' onclick='test("left");'>
<img src="right.png" width='100' height='100' onclick='test("right");'>
<img src="fire.png" width='100' height='100' onclick='test("fire");'>
</body>
</html>
关于JavaScript 无法在 onclick 属性中找到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881914/