Creating Dynamic button with click event in JavaScript

前端 未结 4 1559
栀梦
栀梦 2020-11-28 07:15

How can I create a dynamic button with a click event with JavaScript?

I tried this, but when I click the add button, an alert message show up! It\'s not what I want

4条回答
  •  爱一瞬间的悲伤
    2020-11-28 08:06

    Firstly, you need to change this line:

    element.setAttribute("onclick", alert("blabla"));
    

    To something like this:

    element.setAttribute("onclick", function() { alert("blabla"); });
    

    Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.

提交回复
热议问题