Ajax 服务器返回html字符串中元素的事件绑定方法

前几天写代码遇到一个纠结的问题,就是使用Ajax技术的时候,服务器返回的HTML字符串中元素的Jquery控制或者说是事件绑定方法失效,但是CSS控制是正常的,而如果不采用Ajax技术,则不会产生这样的问题。后来终于发现,其实Jquery绑定事件的元素是当前页面的元素,而采用Ajax技术后,服务器返回的HTML代码中的元素隶属于另一个页面,此时其中的元素也当然不会被绑定事件。

我们来详细看一下。我们平常为元素绑定事件是这样做的,以我做的实验为例:

在主页面如main.php中加入

 <script type="text/javascript"
	src="<?php
	echo base_url ( "items/js/index/base_all.js" )?>"></script>
然后这个文件中的元素及可以用JS文件中的方法来控制了。假如说我的main.php有这样一段代码:

<div class="product_photo"><a href=""><img
	src=<?php
		echo base_url ( $picture_path );
		?> alt=""
	class="product_focus"></img></a></div>

我想控制img这个元素。并在base_all.js写了这样一段代码:

$(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:"<?php echo site_url("ajax_part/getProductDetail");?>",
		success:function(data)
		{$(".just").empty();
			$(".just").html(data);
			
		}
		
	});

其中data就是这段html代码,就会不起效果。这大概就是我当初遇到的问题,其实细细想想解决这个问题其实不难,既然Jquery只能给当前页面的元素绑定事件,那么我们就可以在Ajax返回的HTML字符串载入到当前页面后对其元素进行事件的重新绑定。方法就是这样:

不用包含base_all.js这个JS文件,而把其中的Jquery控制代码写入$.ajax中。如下:

$.ajax({
		type:"POST",
		url:"<?php echo site_url("ajax_part/getProductDetail");?>",
		success:function(data)
		{
			$(".just").empty();
			$(".just").html(data);
			afterLoad();
			
		}
		
	});
function afterLoad()
{
	$(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();
		});
}


将Jquery放在页面载入Html字符串之后。为元素重新绑定事件就可以了。。



  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值