添加onclick事件动态添加按钮?

san*_*eev 13 html javascript forms

我在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;
Run Code Online (Sandbox Code Playgroud)

有没有办法解决这个问题?Plz帮助我.,提前谢谢

jer*_*jer 20

试试这个:

but.onclick = callJavascriptFunction;
Run Code Online (Sandbox Code Playgroud)

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

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

  • 如何将callms添加到callJavascriptFunction(),如callJavascriptFunction(p1,p2,p3) (3认同)

Bre*_*ker 11

从表达式中删除无效的()将获得所需的结果.

but.setAttribute("onclick",callJavascriptFunction);
but.onclick= callJavascriptFunction;
document.getElementById("but").onclick=callJavascriptFunction;
Run Code Online (Sandbox Code Playgroud)


小智 7

这段代码对我很好,看起来更简单。需要调用具有特定参数的函数。

var btn = document.createElement("BUTTON");  //<button> element
var t = document.createTextNode("MyButton"); // Create a text node
btn.appendChild(t);   

btn.onclick = function(){myFunction(myparameter)};  
document.getElementById("myView").appendChild(btn);//to show on myView
Run Code Online (Sandbox Code Playgroud)


Niv*_*vas 5


but.addEventListener('click', yourFunction) 注意函数名称后没有括号()。这是因为您正在分配函数,而不是调用它。


ken*_*ruz 5

but.onclick = function() { yourjavascriptfunction();};

或者

but.onclick = function() { functionwithparam(param);};