添加onclick事件来动态添加按钮? [英] adding onclick event to dynamically added button?

查看:180
本文介绍了添加onclick事件来动态添加按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在html中动态添加一个按钮,如下所示:
单击该按钮我想调用一个Javascript函数:

I am adding a button dynamically in html like below: On click of that button I want to call a Javascript function:

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;

有没有什么办法可以解决这个问题?? Plz帮助我,
先谢谢了

Are there any ways to resolve this??Plz help me., thanks in advance

推荐答案

试试这个:

try this:

but.onclick = callJavascriptFunction;

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

or create the button by wrapping it with another element and use innerHTML:

var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';

这篇关于添加onclick事件来动态添加按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆