JavaScript 无法在 onclick 属性中找到函数

标签 javascript html image

我的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/

相关文章:

wpf - WPF中图像的淡入淡出

javascript - 为什么经度/纬度加权计算在 JavaScript 中给出与 SQL 不同的结果

javascript - 实际 <DIV> 大小比预期的大

javascript - JQuery/JavaScript : Is it possible do this (watch link below) with simple image on webpage?

Javascript:获取图像中点击的 X、Y 坐标

html - CSS-Bug 在滚动时导致重复元素

image - 使用 Ghostscript 将 PDF 转换为 JPG

javascript - 如何在 UIAutomation iOS 的 javascript 中获取文件内容(基本上读取)本地文件

javascript - Accordion slider 在单击其他选项卡时不会关闭上一个选项卡

javascript - 将数组值赋给变量