我有一个脚本,每隔5秒在一个表格中创建一个按钮。
我最初使用onclick
属性创建了一个按钮,该按钮在脚本中调用了一个函数。然而,这给了我一个错误,说这个功能并不存在,而且从我在这里看到的,它已被回答,但我不知道我是如何解决的在我的情况下。我切换它,以便Javascript处理按钮单击。我在按钮标记中添加了属性,以便在调用btnTeamListAction
函数时获取。控制台打印以下内容,
control.js:86 Uncaught TypeError:无法设置属性' onclick'为null 在window.onload(control.js:86)
JS Snippets:
#button click handler
btnTeamListAction.onclick = function(){
var id = this.getAttribute("data-team-id");
var isRedo = this.getAttribute("data-is-redo");
teamListSelect(id,isRedo);
}
#the function that creates the buttons
function appendTeamTable(id,name,finished){
var finished_txt;
var action_content;
if(finished == 1){
finished_txt = "Yes";
action_content = '<button id="teams-list-action" data-team-id="'+id+'" data-is-redo="1">Retime</button>';
}
else {
finished_txt = "No";
action_content = '<button id="teams-list-action" data-team-id="'+id+'" data-is-redo="0">Time</button>';
}
var tr = document.createElement('tr');
tr.innerHTML ='<td>'+ id +'</td><td>'+ name +'</td><td>'+ finished_txt +'</td><td>'+ action_content +'</td>'
teamTable.appendChild(tr);
var btnTeamListAction = document.getElementById("teams-list-action");
btnTeamListAction.onclick = function(){
console.log("ActionClicked");
var id = this.getAttribute("data-team-id");
var isRedo = this.getAttribute("data-is-redo");
teamListSelect(id,isRedo);
}
}
我已尝试浏览此表单以查找此错误并找到了许多相关问题,但不是因为这个按钮是由JS本身创建的。 请询问您是否需要完整的脚本或HTML,谢谢!
答案 0 :(得分:0)
function appendTeamTable(id,name,finished){
var finished_txt;
var action_content= document.createElement("a");
var btn = document.createElement("button");
btn.setAttribute("id","teams-list-action");
btn.setAttribute("data-team-id",id);
if(finished == 1){
finished_txt = "Yes";
var t = document.createTextNode("Retime");
btn.setAttribute("data-is-redo","1");
}
else {
finished_txt = "No";
var t = document.createTextNode("Time");
btn.setAttribute("data-is-redo","0");
}
btn.appendChild(t);
btn.addEventListener("click",function(){
var id = this.getAttribute("data-team-id");
var isRedo = this.getAttribute("data-is-redo");
teamListSelect(id,isRedo);
});
action_content.appendChild(btn);
var tr = document.createElement('tr');
var td = document.createElement('td');
td.appendChild(action_content);
tr.innerHTML ='<td>'+ id +'</td><td>'+ name +'</td><td>'+ finished_txt +'</td>'
tr.appendChild(td);
teamTable.appendChild(tr);}