<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 4 年前。
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 4 年前。
我对 innerHTML 和 onclick
有问题...
我收到此错误:意外语法错误:参数列表后缺少 )
问题是:
let parent = document.getElementById("parent");
let a, b;
function addDivs(){
a = 5;
b = 7;
parent.innerHTML += "<div onclick='callFunc("+a+","+b+")'></div>";
}
function callFunc(x, y){
console.log(x+y);
}
<div id="parent">
</div>
最佳答案
您发布的代码中的主要问题是没有将调用 addDivs()
的点击事件附加到父级 div
,当您修复它时一切正常,附加使用 addEventListener()
的事件,例如:
let parent = document.getElementById("parent");
let a, b;
parent.addEventListener('click', addDivs, false);
function addDivs() {
a = 5;
b = 7;
parent.innerHTML += "<div onclick='callFunc(" + a + "," + b + ")'>NEW DIV</div>";
}
function callFunc(x, y) {
console.log(x + y);
}
<div id="parent">PARENT DIV</div>
关于javascript - 用函数在js中写html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52985564/