Add event to button with javascript

后端 未结 4 1243
忘掉有多难
忘掉有多难 2020-12-18 23:24

In this page there\'s a way to dynamic add html (textbox,input button and radio elements with javascript

my questioon is how can i add an event to the button, imagi

相关标签:
4条回答
  • 2020-12-18 23:43

    Probably the easiest cross-browser way is to set the event name as a property of the element:

    Element.onclick = function () 
    {
       // do something...
    }
    Element.onmouseup = function () 
    {
       // do something else...
    }
    
    0 讨论(0)
  • 2020-12-18 23:44

    Simply, use addEventListener method:

    buttonRef.addEventListener("click", function() {
        alert("Blah blah...");
    }, false);
    

    (You'll have to Google for cross-browser solution. IE doesn't support addEventListener)

    Where buttonRef is a reference to button. How can you get that reference? There's lots of ways to do that. You can use document.getElementById() or any other method from this "family".

    0 讨论(0)
  • 2020-12-18 23:51
    var element = document.createElement("input");
    element.onclick = function() {alert('Clicked!');};
    
    0 讨论(0)
  • 2020-12-18 23:55

    You have to attach the new event when creating the DOM element.

    For example :

    var e = document.createElement('input');
    e.onclick = function()
                {
                   alert('Test');
                };
    
    0 讨论(0)
提交回复
热议问题