jquery中的live和on方法

來源:互聯網
上載者:User

    jQuery 1.10之前的版本有一個.live()方法,這個方法和bind的重要區別就是.live()方法可以對以後再添加進來的有效

例如如下的HTML:

<html xmlns="http://www.w3.org/1999/xhtml"><head><title>  </title><script src="jquery-1.8.0.js" type="text/javascript"></script> <body><span>Hello</span><br/> <input type="button" id="btnCancel" class="button" value="測試" onclick="javascript:test()" /> <div id="testdiv"></div></body></html>

使用bind方法:

$(document).ready(function () { $('span').bind('click',function() {           alert( "333" );   })});  function test(){ $("#testdiv").append("<span>Hello</span><br/>");}

則只有已經存在的那一個span能綁定上 click事件,對於通過test()後添加的span是沒有綁定click事件的,如果還需要給後來添加的span綁定則必須重新綁定一次 例如:
$(document).ready(function () { $('span').bind('click',function() {           alert( "333" );   })});  function test(){ $("#testdiv").append("<span>Hello</span><br/>"); $("span").unbind( "click" )// 去掉原來的綁定 $('span').bind('click',function() {//重新綁定           alert( "333" );       })

這樣以後 通過 test() 後添加的 span也就綁定了事件。
其實還有更簡單的方法,就是使用live,例如:
$(document).ready(function () { $('span').live('click',function() {           alert( "333" );   })});  function test(){ $("#testdiv").append("<span>Hello</span><br/>");}

但在  jQuery 1.10之後,沒有了live方法,變成了on方法,如何使用呢。
$(document).ready(function () { $('span').on('click',function() {           alert( "333" );   })});  function test(){ $("#testdiv").append("<span>Hello</span><br/>");} 

測試發現,還是只對存在的span綁定的方法,通過 test() 後添加的 span是沒有綁定 click事件的,那對於使用live方法綁定的如何替換呢。 其實可以這樣寫:
$(document).ready(function () { $(document).on('click', 'span', function() {           alert( "333" );}) });function test(){ $("#testdiv").append("<span>Hello</span><br/>"); }

當然也可以這樣寫:
$(document).ready(function () { $("body").on('click', 'span', function() {           alert( "333" );}) });function test(){ $("#testdiv").append("<span>Hello</span><br/>"); }

本質其實是綁定在了父元素(body)上,再根據父元素找滿足條件的子項目(span),這樣效能就會有所提升,所以替換live方法,就需要使用on在父元素的綁定,而不是簡單的把字元live替換為on

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.