javascript – 将onclick事件添加到动态添加按钮?

前端之家收集整理的这篇文章主要介绍了javascript – 将onclick事件添加到动态添加按钮?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在html中动态添加一个按钮,如下所示:
点击该按钮我想调用一个 Javascript功能
var but = document.createElement("button");

but.value="delete row";

but.setAttribute("onclick","callJavascriptFunction()");
//this is not working

but.onclick="callJavascriptFunction()"
//this is also not working

document.getElementById("but").onclick="callJavascriptFunction()"
//this is also not working

but.id="but"+inc;

有什么办法可以解决这个问题吗?
提前致谢

解决方法

尝试这个:
but.onclick = callJavascriptFunction;

或者通过用另一个元素包装来创建按钮,并使用innerHTML:

var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';
原文链接:https://www.f2er.com/js/153908.html

猜你在找的JavaScript相关文章