我有以下代码片段。
function createTable(channelArr, id) {
console.log(channelArr)
var table = document.getElementById("channelsTable");
for (i = 0; i < channelArr.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
let inverseIndex = channelArr.length - 1 - i
cell1.innerHTML = "# " + channelArr[inverseIndex].name
var checkbox = '<input type="checkbox" onclick="toggleCheckbox()" id="complete" checked="false">';
cell2.innerHTML = checkbox
if (channelArr[i].members.indexOf(id) != -1) {
document.getElementById("complete").checked = true;
}
}
}
function toggleCheckbox() {
console.log("clicked")
}
表中的每个复选框都有一个onchange处理程序(toggleCheckbox)。但是,当我尝试单击复选框时,我收到以下错误。
Uncaught ReferenceError: toggleCheckbox is not defined at HTMLInputElement.onclick (pick_channels?token=...)
非常感谢任何有关这种情况的帮助。
答案 0 :(得分:1)
我将代码更改为此代码并且有效。
function createTable(channelArr, id) {
console.log(channelArr)
var table = document.getElementById("channelsTable");
for (i = 0; i < channelArr.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
let inverseIndex = channelArr.length - 1 - i
cell1.innerHTML = "# " + channelArr[inverseIndex].name
var checkbox = document.createElement("INPUT");
checkbox.type = "checkbox";
checkbox.onchange = () => checkClicked(inverseIndex);
if (channelArr[i].members.indexOf(id) != -1) {
checkbox.checked = true
}
cell2.appendChild(checkbox)
}
}
答案 1 :(得分:0)
您可以使用您已经定义的引用来定义是否应该检查并绑定事件:
var checkbox = '<input type="checkbox" id="complete" checked="false">';
document.getElementById('container').innerHTML = checkbox;
checkbox = document.getElementById("complete");
checkbox.checked = false;
checkbox.onclick = toggleCheckbox.bind(this);
答案 2 :(得分:0)
复选框只有两个状态true
或false
,因此请尝试将代码更改为
function createTable(channelArr, id) {
console.log(channelArr)
var table = document.getElementById("channelsTable");
for (i = 0; i < channelArr.length; i++) {
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
let inverseIndex = channelArr.length - 1 - i
cell1.innerHTML = "# " + channelArr[inverseIndex].name
var checkbox = '<input type="checkbox" onclick="toggleCheckbox('+i+')" id="'+i+'" checked="false">';
cell2.innerHTML = checkbox
if (channelArr[i].members.indexOf(id) != -1) {
document.getElementById("complete").checked = true;
}
}
}
function toggleCheckbox(id) {
console.log("clicked id "+id);
}