html js 動態綁定函數

來源:互聯網
上載者:User

1、綁定到元素,這也是比較常見的一種比如: 
  <input type="button" onclick="doEventThing(event)">    
觸發:擊此按鈕
2、綁定事件到對象:這也是比較常見的一種,特別是在IE4+下面: 
  document.getElementById("divid").onclick = doEventThing; 
3、使用<script for>進行事件的綁定,這隻在IE4+下有用(為button1綁定事件,邏輯在script塊中書寫event來指定怎麼觸發事件):

  <script event="onclick" for="button1"> 
 // script statements here 
</script>

4、使用 IE5/Windows 的 attachEvent() 方法      

  document.attachEvent('onmousedown', popup_mousepos);

      可以參考這裡
5、使用 W3C DOM 的 addEventListener() 方法
  addEventListener("eventType",listenerReference,captureFlag); 
  第三個參數則是一個 Boolean 值,指明該結點是否以DOM中所謂的捕捉模式來偵聽事件。對於一個典型的事件接聽程式來說,第三個參數應該為false(假)。

prototype在綁定事件的時候相容IE和W3C的時候做的處理如下:

  _observeAndCache: function(element, name, observer, useCapture) {    

    if (!this.observers) this.observers = [];     
      if (element.addEventListener) {//W3C DOM     
           this.observers.push([element, name, observer, useCapture]);     
           element.addEventListener(name, observer, useCapture);    

      } else if (element.attachEvent) {//IE5/Windows     
           this.observers.push([element, name, observer, useCapture]);     
           element.attachEvent(’on’ + name, observer);     
        }     
    }
撇開this.observers.pust([element,name,observer,useCapture])不談,我們對4、5所說的事件綁定就很清楚了。我們知道prototype的此方法的useCapture在IE下沒有作用,只

對W3C的事件處理機制起作用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.