解决用jquery load加载页面到div时,不执行页面js的问题

来源:互联网 发布:jquery能储存数据不 编辑:程序博客网 时间:2024/05/18 04:50
  • 使用.bind()方法是很浪费资源的,因为它要匹配选择器中的每一项并且挨个设置相同的事件处理程序
  • 建议停止使用.live()方法,因为它已经被弃用了,由于他有很多的问题
  • .delegate()方法“很划算”用来处理性能和响应动态添加元素的时候
  • 新的.on()方法主要是可以实现.bind() .live() 甚至 .delegate()的功能
  • 建议使用.on()方法,如果你的项目使用了1.7+的jQuery的话
html代码: 
<div id="header">
js的代码: 
$(document).ready(function(){  $('#header').load('common/header.html');
  $('.dropdown').hover(function(){    $(this).children('ul').slideDown();  },function(){    $(this).children('ul').slideUp();  });
});
只针对网页里面本来就有的元素有效,通过Ajax页面load加载进来的挂在DOM树上的元素只能通过事件委托来实现
js修改后的代码:
$(document).ready(function(){  $('#header').load('common/header.html');
  $('#header').on('mouseenter','.dropdown',function(){    $(this).children('ul').slideDown();  }).on('mouseleave','.dropdown',function(){    $(this).children('ul').slideUp();  });
});


0 0