生活随笔
收集整理的這篇文章主要介紹了
ajax传向前台的html代码里又有事件的时候,绑定事件失败解决方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為動態添加的元素綁定事件有以下幾種方式:
1.delegate():向匹配元素的當前或未來的子元素附加一個或多個事件處理器
$(
selector).delegate(
childSelector,
event,
data,
function)
目前大多數jquery版本都可用,不過我一般不用它。
[javascript] view plaincopy
?$("#searchMoveVideoResult").delegate("ul?li","click",function(){??????$(this).css("border","5px?solid?#000");??});??
[javascript] view plaincopy
$("#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()方法綁定事件。
[javascript] view plaincopy
$("#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");??});??
??
$("#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;">οnclick="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);??????????????}??????????}??????});????}?
總結
以上是生活随笔為你收集整理的ajax传向前台的html代码里又有事件的时候,绑定事件失败解决方法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。