Difference between “click” and onclick

前端 未结 3 1087
无人及你
无人及你 2020-12-10 16:24

What is the difference between click in

document.getElementById(\"myBtn\").addEventListener(\"click\", displayDate);    

and onclick in

3条回答
  •  粉色の甜心
    2020-12-10 16:55

    The difference is that the first is an event listener, and the second is an event handler content attribute.

    Event handler content attributes store an internal raw uncompiled handler, which produces an event listener via the event handler processing and getting the current value of the event handler algorithms.

    In practice, this affects the scope, e.g.

    (function() { var element = document.body;
      var str = "console.log([typeof foo, typeof bar])";
      var func = function() { console.log([typeof foo, typeof bar]); };
      element.foo = 'foo';
      var bar = 'bar';
      element.setAttribute('onclick', str);
      element.addEventListener('click', func);
      element.click();
      // Event handler content attribute logs ["string", "undefined"]
      // Event listener logs ["undefined", "string"]
    })();
    

    I discourage using event handlers. They are an old reminiscence and are superseded by event listeners.

提交回复
热议问题