原型 - 事件觀察 () 方法



此方法在 DOM 元素上註冊一個事件處理程式。

要將一個函式註冊為事件處理程式,您想觀察的 DOM 元素必須已經存在於 DOM 中。

語法

Event.observe(element,eventName,handler[,useCapture=false]);

以下是有關傳遞的引數的說明 -

  • element - 您希望觀察的 DOM 元素;與 Prototype 中一樣,這可以是實際的 DOM 引用,也可以是該元素的 ID 字串。

  • eventName - 標準化的事件名稱,根據瀏覽器支援的 DOM 級別而定。這包括單擊、滑鼠按下、滑鼠鬆開、滑鼠移入、滑鼠移動和滑鼠移出。

  • handler - 這是事件處理程式函式。這可以是您隨時建立的匿名函式。

  • useCapture - 或者,您可以請求捕獲而不是冒泡。詳情請見 http://www.w3.org/TR/DOM-Level-2Events/events.html

返回值

不適用。

示例

下面是一個示例,它觀察單擊事件,並在發生單擊事件時採取措施。

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         // Register event 'click' and associated call back.
         Event.observe(document, 'click', respondToClick);
  
         // Callback function to handle the event.
         function respondToClick(event) {
            alert("You pressed the button...." );
         }
      </script>
   </head>

   <body>
      <p id = "note"> Click anywhere to see the result.</p>
      <p id = "para1">This is paragraph 1</p>
      <p id = "para2">This is paragraph 2</p>
      <div id = "division">This is divsion.</div>
   </body>
</html>

輸出

prototype_event_handling.htm
廣告
© . All rights reserved.