Ajax 服务器返回html字符串中元素的事件绑定方法
Ajax 服务器返回html字符串中元素的事件绑定方法分类:JavaScript2012-02-25 21:463951人阅读评论(2)收藏举报 ajaxhtml服务器functionjqueryurl 前几天写代码遇到一个纠结的问题,就是使用Ajax技术的时候,服务器返回的HTML字符串中元素的Jquery控制或者说是事件绑定方法失效,但是CSS控制是正常的,而如果不采用Ajax技术,则不会产生这样的问题。后来终于发现,其实Jquery绑定事件的元素是当前页面的元素,而采用Ajax技术后,服务器返回的HTML代码中的元素隶属于另一个页面,此时其中的元素也当然不会被绑定事件。 我们来详细看一下。我们平常为元素绑定事件是这样做的,以我做的实验为例: 在主页面如main.php中加入 [javascript]view plaincopy
然后这个文件中的元素及可以用JS文件中的方法来控制了。假如说我的main.php有这样一段代码: [php] <divclass="product_photo"><ahref=""><img src='#'" /span> echobase_url($picture_path); ?>alt="" class="product_focus"></img></a></div>
$(function(){ $(".product_focus").bind( 'mouSEOver', function(){ $(this).parent().parent().parent().parent().parent().children( '.product_display').css( { top:$(this).position().top+"px", left:$(this).position().left-15 +$(this).outerWidth(false)+"px" }); $(this).parent().parent().parent().parent().parent().children( '.product_display').show(); }); $(".product_focus").bind('mouseleave',function(){ $(".product_display").hide(); }); });
但是如果main.php中的这段代码是Ajax服务器返回的,Jquery特效就不会起一点作用。 如:
$.ajax({ type:"POST", url:"<?phpechosite_url("ajax_part/getProductDetail");?>", success:function(data) {$(".just").empty(); [javascript] $(".just").html(data); } });
不用包含base_all.js这个JS文件,而把其中的Jquery控制代码写入$.ajax中。如下: function(data) { $(".just").empty(); $(".just").html(data); afterLoad(); } }); [javascript] functionafterLoad() { $(function(){ $(".product_display").hide(); }); }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |