首页 > 其他 > 详细

Event Listeners

时间:2016-04-18 13:22:59      阅读:166      评论:0      收藏:0      [点我收藏+]

Event Listeners

The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.
You can add many event handlers to one element.
You can add many event handlers of the same type to one element, i.e., two "click" events.element.addEventListener(event, function, useCapture);
The first parameter is the event‘s type (like "click" or "mousedown").
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional, and will be described in the next lesson.
Note that you don‘t use the "on" prefix for the event; use "click" instead of "onclick".
Example:

element.addEventListener("click", myFunction);
element.addEventListener("mouseover", myFunction);

function myFunction() {
  alert("Hello World!");
}

 
This will add two event listeners to the element.
We can remove one of the listeners:

element.removeEventListener("mouseover", myFunction);

 
Let‘s create an event handler that removes itself after being executed:

<html>
<body>
  <button id="demo">
   Start
  </button>

  <script>
  var btn = document.getElementById("demo");
  btn.addEventListener("click", myFunction);

  function myFunction() {
   alert(Math.random());
   btn.removeEventListener("click", myFunction);
  }
</script>

</body>
</html>

Event Listeners

原文:http://www.cnblogs.com/guojunru/p/5403779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!