jQuery-為動態添加的元素繫結事件

來源:互聯網
上載者:User

標籤:strong   指令碼   live   oca   location   comm   tools   錯誤   click   

範例:

$("#modify_nick").click(function () {
$(this).css("display","none");
$("#nickname_span").empty();
var input = document.createElement("input");
$(input).attr("type", "text");
$(input).attr("id", "user_nick_id");
$(input).attr("name", "user_nick");
$(input).attr("maxlength", "20");
$(input).attr("value", "<?php echo $userinfo->nickname ?>");
$(input).appendTo("#nickname_span");
$(input).focusEnd();
});

$("#nickname_span").on("blur","input[name=‘user_nick‘]",function(){
var startVal = "<?php echo $userinfo->nickname ?>";
var endVal = $(this).val();
$("#modify_nick").css("display","block");
if(endVal != startVal){
if(endVal != ""){
$.ajax({
type: "GET",
url: "<?php echo Yii::app()->createUrl(‘user/modifyUserInfo‘) ?>",
data: {user_nick: endVal},
dataType: "json",
success: function (msg) {
if(msg == 666){
window.location.href = "<?php echo Yii::app()->createUrl(‘user/userManager‘) ?>";
}
}
});
}
}
});

說明:

在使用jQuery的方式為元素繫結事件時,我經常使用bind或者click,但這隻能為頁面已經載入好的元素繫結事件。像需要用ajax的方式請求遠端資料來動態添加頁面元素時,顯然以上幾種綁定事件的方式是無效的,具體寫法如。

 

$(selector).bind(event,data,function)
$(selector).click(function)

 

 

[javascript] view plain copy 
  1. $("#searchMoveVideoResult ul li").bind("click",function(){  
  2.     $(this).css("border","5px solid #000");  
  3. });  
  4. $("#searchMoveVideoResult ul li").click(function(){  
  5.     $(this).css("border","5px solid #000");  
  6. });  

 

為動態添加的元素繫結事件有以下幾種方式:

 

1.delegate():向匹配元素的當前或未來的子項目附加一個或多個事件處理器

$(selector).delegate(childSelector,event,data,function)

 

目前大多數jquery版本都可用,不過我一般不用它。

 

[javascript] view plain copy 
  1.  $("#searchMoveVideoResult").delegate("ul li","click",function(){  
  2.     $(this).css("border","5px solid #000");  
  3. });  
[javascript] view plain copy 
  1. $("#searchMoveVideoResult").delegate("click","ul li",function(){  
  2.     $(this).css("border","5px solid #000");  
  3. });  
看出它們的不同了嗎,第二種寫法是錯誤的,記住一定要把事件寫在元素的後面。

 


2.live():為當前或未來的匹配元素添加一個或多個事件處理器

 

$(selector).live(event,data,function)

 

jquery1.8版本以前推薦使用該方法;jquery1.8版本之後就不建議使用了,我試了下,也是無效的,所以高版本的jquery推薦使用on()方法綁定事件。

[javascript] view plain copy 
  1. $("#searchMoveVideoResult ul li").live("click",function(){  
  2.      $(this).css("border","5px solid #000");  
  3. });  

 

 

3.on():適用於當前及未來的元素(比如由指令碼建立的新元素)

 

$(selector).on(event,childSelector,data,function,map)

 

 


實驗了下,大多數版本的jquery都是支援這個方法的,也是我比較喜歡使用的方法。

 

[javascript] view plain copy 
  1. $("#searchMoveVideoResult").on("click","ul li",function(){  
  2.     $(this).css("border","5px solid #000");  
  3. });  
[javascript] view plain copy 
  1. //下面這樣寫就是錯的了,一定要把動態添加的元素放到on()方法裡面才行。</span>  
[javascript] view plain copy 
  1. $("#searchMoveVideoResult ul li").on("click",function(){  
  2.     $(this).css("border","5px solid #000");  
  3. });  

4.onclick事件:動態添加資料時,就為元素繫結onclick事件
[javascript] view plain copy 
    1. function searchMoveVideo(){  
    2.     $.ajax({  
    3.         type:"POST",  
    4.         url:"http://op.juhe.cn/onebox/movie/video",  
    5.         data:{"q":$("#moveVideo").val(),"key":"346f79df993776748b242236464d565d"},  
    6.         dataType:"JSONP",  
    7.         success:function(data){  
    8.             console.log(data);  
    9.             if(data.error_code=="0"){  
    10.                 var result=data.result;  
    11.                 console.log(result);  
    12.                 var html=result.title+"<br>"+result.tag+"<br>"+result.act+"<br>"+result.year+"<br>"                                          +result.area+"<br>"+result.dir+"<br>"+result.desc;  
    13.                 html+="<br><img src=‘"+result.cover+"‘/><br>";  
    14.                 html+=‘<ul style="list-style: none; float: left;">‘;  
    15.                 var act_s=result.act_s;  
    16.                 for(var i=0;i<act_s.length;i++){  
    17.                     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>‘;  
    18.                 }  
    19.                 html+=‘</ul>‘  
    20.                 $("#searchMoveVideoResult").html(html);  
    21.             }else{  
    22.                 $("#searchMoveVideoResult").html(data.reason);  
    23.             }  
    24.         }  
    25.     });    }  

jQuery-為動態添加的元素繫結事件

相關文章

聯繫我們

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