本文實例講述了jQuery實現為動態添加的元素綁定事件。分享給大家供大家參考,具體如下:
在使用jquery的方式為元素綁定事件時,我經常使用bind或者click,但這只能為頁面已經加載好的元素綁定事件。像需要用ajax的方式請求遠程數據來動態添加頁面元素時,顯然以上幾種綁定事件的方式是無效的,具體寫法如下。
$(selector).bind(event,data,function)
$(selector).click(function)
$("#searchMoveVideoResult ul li").bind("click",function(){  $(this).css("border","5px solid #000");});$("#searchMoveVideoResult ul li").click(function(){  $(this).css("border","5px solid #000");});為動態添加的元素綁定事件有以下幾種方式:
1. delegate():向匹配元素的當前或未來的子元素附加一個或多個事件處理器
$(selector).delegate(childSelector,event,data,function)
目前大多數jquery版本都可用,不過我一般不用它。
$("#searchMoveVideoResult").delegate("ul li","click",function(){  $(this).css("border","5px solid #000");});$("#searchMoveVideoResult").delegate("click","ul li",function(){  $(this).css("border","5px solid #000");});看出它們的不同了嗎,第二種寫法是錯誤的,記住一定要把事件寫在元素的后面。
2. live():為當前或未來的匹配元素添加一個或多個事件處理器
$(selector).live(event,data,function)
jquery1.8版本以前推薦使用該方法;jquery1.8版本之后就不建議使用了,我試了下,也是無效的,所以高版本的jquery推薦使用on()方法綁定事件。
$("#searchMoveVideoResult ul li").live("click",function(){   $(this).css("border","5px solid #000");});3. on():適用于當前及未來的元素(比如由腳本創建的新元素)
$(selector).on(event,childSelector,data,function,map)
試驗了下,大多數版本的jquery都是支持這個方法的,也是我比較喜歡使用的方法。
$("#searchMoveVideoResult").on("click","ul li",function(){  $(this).css("border","5px solid #000");});//下面這樣寫就是錯的了,一定要把動態添加的元素放到on()方法里面才行。$("#searchMoveVideoResult ul li").on("click",function(){  $(this).css("border","5px solid #000");});4.onclick事件:動態添加數據時,就為元素綁定onclick事件
function searchMoveVideo(){  $.ajax({    type:"POST",    url:"http://op.juhe.cn/onebox/movie/video",    data:{"q":$("#moveVideo").val(),"key":"346f79df993776748b242236464d565d"},    dataType:"JSONP",    success:function(data){      console.log(data);      if(data.error_code=="0"){        var result=data.result;        console.log(result);        var html=result.title+"<br>"+result.tag+"<br>"+result.act+"<br>"+result.year+"<br>"                     +result.area+"<br>"+result.dir+"<br>"+result.desc;        html+="<br><img src='"+result.cover+"'/><br>";        html+='<ul style="list-style: none; float: left;">';        var act_s=result.act_s;        for(var i=0;i<act_s.length;i++){          html+='<li style="float: left;" <span style="color:#cc0000;">onclick="showSource(this);"</span>><a target="_bla                        nk"><img src="'+act_s[i].image+'"><br>'+act_s[i].name+'</a></li>';        }        html+='</ul>'        $("#searchMoveVideoResult").html(html);      }else{        $("#searchMoveVideoResult").html(data.reason);      }    }  });}            
新聞熱點
疑難解答
圖片精選