前几天写代码遇到一个纠结的问题,就是使用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字符串之后。为元素重新绑定事件就可以了。。