繁体   English   中英

即使在定义函数后,onclick属性也不起作用

[英]onclick attribute not working even after the function is defined

我通过使用这样的for循环动态填充html

function htmlpopulate() {
  /*some DOM manipulations*/
  setInterval(loadhtml, 5000); //getting live data
}

function loadhtml {
  activediv.innerHTML = '';
  for (i = 0; i < userarray.length; i++) {
    var temp = userarray[i].trim();
    activediv.innerHTML += '<p onclick="makecall(' + "'" + temp + "'" + ');return false;")">' + temp + '</p><br/>';
  }
}

function makecall(data) {
  console.log(data);
}

输出: 未定义makecall
如何使内联函数调用该已定义函数?

function makecall必须在全局上下文中定义:

window.makecall = function (data) {
  console.log(data);
};

另外,您还需要整理引号和括号

activediv.innerHTML += '<p onclick="makecall(' + "'" + temp + "'" + 
  ');return false;")">' + temp + '</p><br/>';

您不需要)“ 返回false后;”

以下是JSFiddle,它表示具有click功能的动态创建的按钮。

如果您无法绑定功能,也可以尝试以下方法:

document.getElementById("btnID").onclick = makeCall;

 function createHTML(){ var div = document.getElementById("content"); var _html = ""; for(var i=0; i<5;i++){ _html += "<button onclick='notify("+i+")'>btn " + i +"</button>"; } div.innerHTML = _html; } function notify(str){ console.log("Notify" + str); } function print(data) { console.log(data); } function registerEvent(){ var btnList = document.getElementsByTagName("button"); document.getElementById("btnID").onclick = function(){ print(btnList) }; } (function(){ createHTML(); registerEvent(); })() 
 <div id="content"></div> <button id="btnID">BTN ID</button> 

在那里,您正在定义makecall() ,但是您需要随后实际调用它,如下所示:

makecall(the data you want to use);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM