javascript 如何在 pjax 加载之前和之后运行 jQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10713546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:47:31  来源:igfitidea点击:

How to run jQuery before and after a pjax load?

javascriptjqueryajaxpjax

提问by Dan

I'm currently using pjax and it works great but I need to run two jQuery functions, one before pjax loads the new url and one after the new url is loaded, how can I do this?

我目前正在使用 pjax,它运行良好,但我需要运行两个 jQuery 函数,一个在 pjax 加载新 url 之前,一个在新 url 加载之后,我该怎么做?

I have tried the following two variations but neither seem to work?

我尝试了以下两种变体,但似乎都不起作用?

First attempt:

第一次尝试:

$("a").pjax("#main").live('click', function(){

    //Function Before Load  
    // Function After Load
})  

Second attempt:

第二次尝试:

$("body").on("click", "a", function(){

    //Function Before Load  

    $(this).pjax("#main");

    //Function After Load   

    return false;
});

回答by Prasenjit Kumar Nag

As they says in their doc herepjaxfires two events for what you need

正如他们在他们的文档中所说,这里pjax会根据您的需要触发两个事件

pjax will fire two events on the container you've asked it to load your reponse body into:

pjax:start - Fired when a pjax ajax request begins.

pjax:end - Fired when a pjax ajax request ends.

pjax 将在您要求它加载响应正文的容器上触发两个事件:

pjax:start - 当 pjax ajax 请求开始时触发。

pjax:end - 当 pjax ajax 请求结束时触发。

And the code example for this

以及这个的代码示例

$('a.pjax').pjax('#main')
$('#main')
  .on('pjax:start', function() { //do what you want to do before start })
  .on('pjax:end',   function() { //after the request ends });

回答by Raab

$("body").on("click", "a", function(){

 $(this).pjax("#main");
 $('a.pjax').pjax('#main')
 $('#main').on('pjax:start', function() { /* your code before ajax load */ });
 $('#main').on('pjax:end',   function() { /* your code after ajax load */ });

  return false;
});