狐狸.fox 2009-08-04 05:53 采纳率: 0%
浏览 27

jQuery AJAX加载问题

I'm trying to load all my website pages using jQuery .load method so, thats how my website looks:

<script type="text/javascript">  
  $(function() {
    $('.link').bind('click', function(e) {
            var page = $(this).attr('href');
            $('#site').addClass('loading');
            $('#content').load(page, function (){
            $('#site').removeClass('loading');
    });

    e.preventDefault();
    return false;
  });

<a href="test.php" class="link">Test</a>

With this code, every link that gets class="link" will load my page on the div #content. Works fine! No problems but when I load the test.php, if i use the class="link" on any link, or button, or whatever, it just does not work and the new page is loaded outside my #content.

Already tried to copy this to the new-loaded file and it doesn't work, anyone got a hint?

Thanks

  • 写回答

1条回答 默认 最新

  • bug^君 2009-08-04 06:01
    关注

    This is because when you bind an event it only binds it to the elements that are in the DOM at that time. So if you add new ones later on they won't be bound to the event you previously attached. Assuming you have jQuery 1.3, it has a built-in function to get around this called live. With it, you can bind an event to all current and future elements. It doesn't support all events, but click it does support.

    So keeping that in mind, you just have to replace this:

    $('.link').bind('click', function(e) {
    

    With this:

    $('a.link').live('click', function(e) {
    

    (I added the a. to the selector because it is much more efficient to specify the tag if at all possible)

    If you don't have jQuery 1.3, you should upgrade as soon as possible. If you can't, check out the livequery plugin which achieves the same thing but in a much less elegant way. Alternatively, you can simply have a function to bind the action and call it everytime you load new data in. All things considered, however, jQuery's live is the best way to do this.

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办