在實際開發中,我們常會動態新增元素。這時就會面臨一個問題:動態產生的元素,能不能擁有我們事先綁定的事件?這正是「前綁定」與「後綁定」的分野。
顧名思義:前綁定指元素「還沒出生」就先綁好一出生就該有的事件(對動態元素也生效);後綁定則是元素產生「之後」才綁,動態新增的元素不會擁有這些事件。以下用範例比較。
頁面元素與一個「建立 a 標籤」的按鈕:
<div id="main"> <a href="#">aaaa</a><br /> <a href="#">bbbb</a><br /> </div> <input type="button" value="建立a標籤" id="btnCreate" />
幾種綁定寫法:
// 1. 後綁定(click 直接綁)——動態新增的元素沒有此事件
$("#main > a").click(function(){ alert($(this).html()); });
// 2. 後綁定(bind)
$("#main > a").bind("click", function(){ alert($(this).text()); });
// 3. 後綁定(bind 多事件)
$("#main > a").bind({
click: function(){ alert($(this).text()); },
mouseover:function(){ $(this).css("background-color", "red"); },
mouseout: function(){ $(this).css("background-color", "white"); }
});
// 建立動態元素
$("#btnCreate").bind({
click: function(){ $("<br /><a href='#'>我是動態建立的</a>").appendTo("#main"); }
});
// 4. 前綁定(delegate)——動態元素也擁有點擊事件
$("#main").delegate("a", "click", function(){ alert($(this).text()); });
// 5. 前綁定(live)——事件源頭是 document
$("#main a").live("click", function(){ alert($(this).text()); });
重點比較:click/bind 屬後綁定,對之後才 append 的元素無效;delegate 與 live 屬前綁定(事件委派),動態元素也能觸發。其中 live 的事件源頭是 document,delegate 則綁在具體元素上,因此 delegate 的效率通常比 live 好。實務上新版 jQuery 建議改用 on() 搭配事件委派來取代兩者。