为动态添加的元素绑定事件有以下几种方式:
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");
- });
$(selector).on(event,childSelector,data,function,map)
试验了下,大多数版本的jquery都是支持这个方法的,也是我比较喜欢使用的方法。
- $("#searchMoveVideoResult").on("click","ul li",function(){
- $(this).css("border","5px solid #000");
- });
- //下面这样写就是错的了,一定要把动态添加的元素放到on()方法里面才行。</span>
- $("#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);
- }
- }
- }); }