jquery on方法 綁定動態元素 出現的問題

以前使用 on 的時候一直是web

$("").on('click','function(){  }') less

以後發現有些時候一直沒法綁定(好比元素動態生成時),查看文檔後發現正確用法應該是函數

$(document).on("change","#pageSize_out",function(){  性能

            if($("#page_out").val()!=0){  this

                $("#pageSize").val($(this).val());  spa

                list();  代理

            }  code

        })  orm

同時,注意接口

As this answers receives a lot of attention, here are two supplementary advises :

1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.

That is, if you're adding an element of class b to an existing element of id a, then don't use

$(document.body).on('click', '#a .b', function(){

but use

$('#a').on('click', '.b', function(){

2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.


on(events,[selector],[data],fn)

events:一個或多個用空格分隔的事件類型和可選的命名空間,如"click"或"keydown.myPlugin" 。

selector:一個選擇器字符串用於過濾器的觸發事件的選擇器元素的後代。若是選擇器爲null或省略,當它到達選定的元素,事件老是觸發。

data:當一個事件被觸發時要傳遞event.data給事件處理函數。

fn:該事件被觸發時執行的函數。 false 值也能夠作一個函數的簡寫,返回false。

替換bind()

當第二個參數'selector'爲null時,on()和bind()其實在用法上基本上沒有任何區別了,因此咱們能夠認爲on()只是比bind()多了一個可選的'selector'參數,因此on()能夠很是方便的換掉bind()

替換live()

在1.4以前相信你們很是喜歡使用live(),由於它能夠把事件綁定到當前以及之後添加的元素上面,固然在1.4以後delegate()也能夠作相似的事情了。live()的原理很簡單,它是經過document進行事件委派的,所以咱們也可使用on()經過將事件綁定到document來達到live()同樣的效果。

live()寫法

$('#list li').live('click', '#list li', function() {
    //function code here.
}); 

on()寫法

$(document).on('click', '#list li', function() {
    //function code here.
});

這裏的關鍵就是第二個參數'selector'在起做用了。它是一個過濾器的做用,只有被選中元素的後代元素纔會觸發事件。

替換delegate()
delegate()是1.4引入的,目的是經過祖先元素來代理委派後代元素的事件綁定問題,某種程度上和live()優勢類似。只不過live()是經過document元素委派,而delegate則能夠是任意的祖先節點。使用on()實現代理的寫法和delegate()基本一致。

delegate()的寫法

$('#list').delegate('li', 'click', function() {
    //function code here.
});

on()寫法

$('#list').on('click', 'li', function() {
    //function code here.
});

貌似第一個和第二個參數的順序顛倒了一下,別的基本同樣。

總結jQuery推出on()的目的有2個,一是爲了統一接口,二是爲了提升性能,因此從如今開始用on()替換bind(), live(), delegate吧。尤爲是不要再用live()了,由於它已經處於不推薦使用列表了,隨時會被幹掉。若是隻綁定一次事件,那接着用one()吧,這個沒有變化。

相關文章
相關標籤/搜索