Handling “onclick” event with pure JavaScript

后端 未结 3 646
旧时难觅i
旧时难觅i 2020-11-29 07:23

So this is really straight forward but I\'m still fairly new to JavaScript and just found JSFiddle. I\'m trying to find the element with the getElementById() t

3条回答
  •  温柔的废话
    2020-11-29 08:06

    All browsers support this (see example here):

    mySelectedElement.onclick = function(e){
        //your handler here
    }
    

    However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener (needs shim for IE8-)

    mySelectedElement.addEventListener("click",function(e){
       //your handler here
    },false);
    

    Here is a working example:

    var button = document.getElementById("myButton");
    button.addEventListener("click",function(e){
        button.disabled = "true";
    },false);
    

    And html:

    
    

    (fiddle)

    Here are some useful resources:

    • addEventListener on mdn
    • The click event in the DOM specification
    • Click example in the MDN JavaScript tutorial

提交回复
热议问题