即使定义了函数,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
如何使内联函数调用 定义的 函数?
在那里,您正在定义 makecall()
,但您需要在之后实际调用它,如下所示:
makecall(the data you want to use);
下面是JSFiddle代表动态创建的带点击功能的按钮。
如果无法绑定函数也可以试试这个:
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>
function makecall
必须在全局上下文中定义:
window.makecall = function (data) {
console.log(data);
};
还有,需要整理一下
中的引号和括号
activediv.innerHTML += '<p onclick="makecall(' + "'" + temp + "'" +
');return false;")">' + temp + '</p><br/>';
你不需要 )" 在 return false;".
我正在使用这样的 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
如何使内联函数调用 定义的 函数?
在那里,您正在定义 makecall()
,但您需要在之后实际调用它,如下所示:
makecall(the data you want to use);
下面是JSFiddle代表动态创建的带点击功能的按钮。
如果无法绑定函数也可以试试这个:
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>
function makecall
必须在全局上下文中定义:
window.makecall = function (data) {
console.log(data);
};
还有,需要整理一下
中的引号和括号activediv.innerHTML += '<p onclick="makecall(' + "'" + temp + "'" +
');return false;")">' + temp + '</p><br/>';
你不需要 )" 在 return false;".