如何在JavaScript中注册事件?

在JavaScript代码中注册事件处理程序可让您使用“ this”语句。无需将值传递给JavaScript函数,而使用“ this”来操纵属性。

让我们看一个例子

<!DOCTYPE html>
<html>
   <head>
      <script>
         function display( ) {
            click.onclick = styleMe;
            uname.onclick = styleMe;
         }
         function styleMe ( ) {
            this.style.backgroundColor = "#000000";
            this.style.color = "#FFFFFF";
         }
      </script>
   </head>
   <body onload="display()" >
      <div id="uname"> Hello Wordl!</div>
      <button id="click"> Click</button>
   </body>
</html>