1. 程式人生 > >jquery on方法 繫結動態元素 出現的問題

jquery on方法 繫結動態元素 出現的問題

               

之前使用 on 的時候一直是

$("").on('click','function(){}')
之後發現有些時候一直無法繫結(比如元素動態生成時),檢視文件後發現正確用法應該是
$(document).on("change","#pageSize_out",function(){         if($("#page_out").val()!=0){          $("#pageSize").val($(this).val());          list();          }        })

同時,注意

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()吧,這個沒有變化。