我希望能够使用setAttribute传递字符串作为按钮的onclick函数的值。单击按钮时出现“未定义添加”的错误,我不确定自己在做什么错。

    var AddButton = document.createElement("button");
    var AddString = "add";
    var SectorString = "1_1";
    AddButton.setAttribute("onclick",'AddOrDeleteDiv(AddString,SectorString)');





   function AddOrDeleteDiv(AddString, SectorString) {
//code
}

最佳答案

不要使用内容属性事件处理程序!改用事件监听器:

var addButton = document.createElement("button");
var addString = "add";
var sectorString = "1_1";
addButton.addEventListener('click', function() {
  addOrDeleteDiv(addString, sectorString);
});
function addOrDeleteDiv(addString, sectorString) {
  //code
}

09-12 21:07