2013-03-25 81 views
1

我有一个函数,它使用ajax来加载我的一个网站的内容。点击功能无法正常工作或改变时

这样做的效果很好,但在某些部分,因为带来了新的内容,有更多的链接我需要使点击功能成为一个实时点击功能,但是当我做ajax停止工作,它只是改变页面正常(没有Ajax)

这里是我的代码

function ajaxLoads(){ 

    var $btn = $('a.ajax-btn'); 
    var $container = $('#load'); 
    var siteTitle = document.title; 
    //var $artistBG = $('#artist-viewport img'); 

    $btn.click(function(e){ 

     console.log(); 

     e.preventDefault(); 
     $btn.removeClass('selected'); 
     //$artistBG.removeClass('top'); 

     var sourceTarget = $(this).data('page'), 
     slideWidth = $container.width(), 
     $this = $(this), 
     $background = $this.data('background'), 
     pageUrl=$this.attr('href'), 
     pageTitle = $this.html(); 
     //$changeTo = $("#artist-viewport img[data-background='"+ $background +"']"); 

     $this.addClass('selected'); 
     //$changeTo.addClass('top'); 
     $container.animate({'right':-slideWidth}, 300, 'easeInExpo'); 

     $container.load(pageUrl+" "+sourceTarget, function(){ 

      subNav(); 

      $("html, body").animate({ scrollTop: 0 }, 500, 'easeInExpo', function(){ 
       $container.animate({'right':0}, 300, 'easeInExpo'); 
      });   

      var pageContent = $(this).html(); 

      window.history.pushState({"html":pageContent, "pageTitle": pageTitle},"", pageUrl); 
      //document.title=pageTitle+" :: "+siteTitle; 

     }); // end load function  

    }); // end click function 

    window.onpopstate = function(e){ 
     if(e.state){ 
      $container.css('opacity', 0).html(e.state.html).fadeTo('fast', 1); 
      document.title=e.state.pageTitle+" :: "+siteTitle; 
     } 
    }; 

} 

我曾试图改变$btn.click(function(e) to $btn.live('click', function(e) and to $btn.on('click', function(e)

+0

您可以使用委托,直播或上。这里是例子http://api.jquery.com/delegate/ – ajay 2013-03-25 11:10:16

回答

2

在文档上添加.on

$(document).on('click','a.ajax-btn',function(){ }); 
1

尝试on

$('#load').on('click', '.ajax-btn', function(){ 
    ... 
}); 

现场被弃用的jQuery 1.8和1.9中删除..所以使用on()

1

给您的按钮CSS类,并使用此

$(document).on("click",".yourcssclass",function(e){}); 

这将默认工作以来,大多数事件冒泡从原始事件目标到文档元素。尽管降低了性能,但点击事件并不经常发生,您可以使用它作为解决问题的方法。然后,当您有时间时,请尝试明白为什么使用委托并非经过仔细处理看你的页面周期。