gpt4 book ai didi

javascript - javascript for 循环中的 DispatchEvent

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

我创建了一个事件,以便可以在事件发生时添加监听器。触发事件的场景会有所不同,因此需要跟踪触发事件的原因并进行适当的处​​理。但是,我尝试在循环内发生的函数中添加dispatchEvent,但收到 InvalidState 错误。任何人都愿意解释导致此错误的原因以及为什么会在这里发生。你可以在下面看到我的代码

//create event
var event = new Event('tableRowAdded');

//get element reference
var table = document.getElementById('dataTable');

//set model
var model = [{jsonData},{jsonData},{jsonData}];

//validate model and then start creating table
function addRowsToTable(DOMTable, rowData){
//stop execution if rowdata null
if(rowData == null || DOMTable == null){
return;
}

var currentRowCount = DOMTable.rows.length;

//add empty row to table
var tr = DOMTable.insertRow(currentRowCount);
tr.id = "data_row_" + currentRowCount;

//add columns to table
//first cell is used for error data
var td = tr.insertCell(0);

//traineeCode
td = tr.insertCell(1);
td.innerHTML = rowData.TRAINEE_CODE; //this is one of the json keys within the json data
}

function populateTableFromJSON(){
var count = model.length;

//loop over json array to populate table
for(i = 0; i < count; i++){
addRowsToTable(table, model[i]);
//dispatch event occured
table.dispatchEvent(event);
}
}

这是收到的错误

Uncaught InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event is already being dispatched.

最佳答案

大概你需要改变:

table.dispatchEvent(event); 

table.dispatchEvent(new Event('tableRowAdded'));

关于javascript - javascript for 循环中的 DispatchEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052453/

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