gpt4 book ai didi

JavaScript fireEvent 不是函数?

转载 作者:行者123 更新时间:2023-11-28 01:40:38 28 4
gpt4 key购买 nike

我一直在尝试用 JavaScript 制作 Battleship 游戏以完成学校作业,但我一直在尝试创建对手 AI。当我点击网格中的单元格时,我创建了一个事件:

function addListener(evt) {
evt.addEventListener('click', function(){
//bunch of code
});
}

现在,每次我在嵌套的 for 循环中的网格中创建一个新单元格时,我都会运行此函数 addListener:

yourCell.setAttribute('id', evt + String(a) + String(b));
addListener(yourCell);

我现在想要的是让对手在轮到我时运行这个点击事件,所以我写这个只是为了测试 fireEvent 函数:

function enemyTurn() {
document.getElementById('yourGrid00').fireEvent('onclick');
}

根据第二个代码示例,我将单元格的 ID 设置为 'yourGrid00',我在运行 JavaScript 代码后通过检查 html 代码确认了这一点,并且函数enemyTurn() 永远不会在每个单元格都被创建并分配一个 ID 之前运行。

我不明白的是,我在 fireEvent 行收到以下错误:

Uncaught TypeError: undefined is not a function.

有人知道我做错了什么吗?

最佳答案

fireEvent 是一种非常古老的方法,仅在 Internet Explorer 8 及更低版本上受支持。您应该改用 dispatchEvent如果您想处理最新的浏览器。

Dispatches an Event at the specified EventTarget, invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) apply to events dispatched manually with dispatchEvent().

您必须手动创建 Event - 您不能只调用 dispatchEvent('onclick')。我从 this answer 中提取了以下代码的第一部分.

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0,
false, false, false, false, 0, null);

function enemyTurn() {
document.getElementById('yourGrid00').dispatchEvent(evt);
}

JSFiddle demo .

关于JavaScript fireEvent 不是函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26335963/

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