JavaScript event registering without using jQuery

前端 未结 6 1325
谎友^
谎友^ 2020-11-29 06:51

How to correctly do something like the following without using jQuery.

   $(document).ready(function(){
      $(\"#someButton\").click(function(){
        al         


        
6条回答
  •  有刺的猬
    2020-11-29 07:17

    This answer isn't so simple without jQuery, because there are two major styles (depending on which browser you are using) for hooking up events. If you don't use one of those two styles, then your events can overwrite each other. Here's the simpler/overwriting style:

    window.onload = function() {
        document.getElementById("someButton").onclick = function() {
            alert("Hello");
        }
    }
    

    But if you try and to the above twice, you'll only get one alert, because the second time will overwrite the first one. Alternatively you can do some browser/feature detection and then use the specific event mechanisms for specific browsers; for more info on that style check out QuirksMode.com:

    http://www.quirksmode.org/js/events_advanced.html

提交回复
热议问题