javascript ajax调用后再次运行jquery函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13879024/
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 20:02:05  来源:igfitidea点击:

Run jquery function again after ajax call

javascriptjqueryajaxrun-script

提问by djwd

Is there any way to run a script again after an ajax call?

有没有办法在ajax调用后再次运行脚本?

I have a photoswipe (lightbox) jquery plug-in I call like this:

我有一个 photowipe (lightbox) jquery 插件,我这样调用:

jQuery(document).ready(function($){

    if( $('.img-frame a').length > 0 ){

        var myPhotoSwipe = $(".img-frame a").photoSwipe();

     }
});

I also have an ajax 'load more posts' function, and obviously photoswipe doesn't target images loaded after the first page load.

我还有一个ajax“加载更多帖子”功能,显然photoswipe不针对第一页加载后加载的图像。

I don't have much ajax knowledge, any help on this? Thanks

我没有太多的ajax知识,这有什么帮助吗?谢谢

UPDATE: Here's the 'load more' script:

更新:这是“加载更多”脚本:

jQuery(document).ready(function($) {

    // The number of the next page to load (/page/x/).
    var pageNum = parseInt(djwd_load_posts.startPage) + 1;

    // The maximum number of pages the current query can return.
    var max = parseInt(djwd_load_posts.maxPages);

    // The link of the next page of posts.
    var nextLink = djwd_load_posts.nextLink;

    /**
     * Replace the traditional navigation with our own,
     * but only if there is at least one page of new posts to load.
     */
    if(pageNum <= max) {
        // Insert the "More Posts" link.
        $('#content')
            .append('<div class="lp-placeholder-'+ pageNum +'"></div>')
            .append('<p id="lp-load-posts" class="long-button"><a href="#">Load More Posts<i class="icon-chevron-down icon-large"></i></a></p>');

        // Remove the traditional navigation.
        $('#nav-below').remove();
    }


    /**
     * Load new posts when the link is clicked.
     */
    $('#lp-load-posts a').click(function() {

        // Are there more posts to load?
        if(pageNum <= max) {

            // Show that we're working.
            $(this).text('Loading posts...');

            $('.lp-placeholder-'+ pageNum).load(nextLink + ' .post',
                function() {

                    $( this ).hide().fadeIn(700);

                    // Update page number and nextLink.
                    pageNum++;
                    nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);

                    // Add a new placeholder, for when user clicks again.
                    $('#lp-load-posts')
                        .before('<div class="lp-placeholder-'+ pageNum +'"></div>')

                    // Update the button message.
                    if(pageNum <= max) {
                        $('#lp-load-posts a').text('Load More Posts');
                    } else {
                        $('#lp-load-posts a').text('No more posts to load.');
                    }
                }
            );
        } else {
            $('#lp-load-posts a').append('.');
        }   

        return false;
    });
});

I call it in Wordpress functions.php this way:

我在 Wordpress functions.php 中这样调用它:

 function djwd_ajax_load_init() {
    global $wp_query;

    if( !is_singular() ) {
        wp_enqueue_script('ajax-load-posts', get_template_directory_uri() . '/js/ajax-load-posts.js', array('jquery'), true );

        $max = $wp_query->max_num_pages;
        $paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;

        wp_localize_script(
            'ajax-load-posts',
            'djwd_load_posts',
            array(
                'startPage' => $paged,
                'maxPages' => $max,
                'nextLink' => next_posts($max, false)
            )
        );
    }
 }
 add_action('template_redirect', 'djwd_ajax_load_init');

采纳答案by iappwebdev

Put it in a function, call in on pageload and in your ajax call.

将它放在一个函数中,在页面加载和 ajax 调用中调用。

function setMyPhotoSwipe() {
    var $targets = $('.img-frame a').not('.photo-swipe');

    if($targets.length > 0 ){
        $targets.addClass('photo-swipe').photoSwipe();
    };
};

jQuery(document).ready(function($){
    setMyPhotoSwipe();
});

By the way, if dont't need variable myPhotoSwipe, then you dont't have to set it. You are also using $('.img-frame a')twice, so cache the result.

顺便说一句,如果不需要变量myPhotoSwipe,那么您不必设置它。您也使用了$('.img-frame a')两次,因此请缓存结果。

And your load call:

你的负载调用:

$('.lp-placeholder-'+ pageNum).load(nextLink + ' .post',
            function() {

                $( this ).hide().fadeIn(700);

                // Update page number and nextLink.
                pageNum++;
                nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);

                // Add a new placeholder, for when user clicks again.
                $('#lp-load-posts')
                    .before('<div class="lp-placeholder-'+ pageNum +'"></div>')

                // Update the button message.
                if(pageNum <= max) {
                    $('#lp-load-posts a').text('Load More Posts');
                } else {
                    $('#lp-load-posts a').text('No more posts to load.');
                }

                // New content has been loaded and insertet, so set up photo swipe
                setMyPhotoSwipe();
            }
        );

回答by A. Wolff

There is no delegation for plugin, its up to author's plugin to incorporate it. Why not cheating: (sorry, cannot test code and not sure its relevant to photoSwipe plugin)

插件没有委托,取决于作者的插件来合并它。为什么不作弊:(抱歉,无法测试代码并且不确定它与 photoSwipe 插件相关)

jQuery(document).ready(function($){

    $(this).on('mousedown','.img-frame a',function(){ //document or better parent container// mousedown or any relevent event use by photoSwipe
          if(!$(this).data('swiped')) {
              $(this).data('swiped',true).photoSwipe();
          }
    });

});

回答by Muhammad Talha Akbar

$.ajax({
    url: 'url/test.php',
    success: function(data) { // also gets response from php and can be manipulated if required!
        setMyPhotoSwipe();
    }
});

回答by Yogesh

Sorry I'm a novice in jquery... How about using ajaxComplete()

抱歉,我是 jquery 的新手...如何使用 ajaxComplete()

http://api.jquery.com/ajaxcomplete/

http://api.jquery.com/ajaxcomplete/

Once I had to execute a function after ajax call... and ajaxComplete() did the trick...

一旦我不得不在 ajax 调用之后执行一个函数……而 ajaxComplete() 就成功了……

$(document).ready(function(){

  function some_function()
  {
  //---- this function to be called after ajax request...
  }

  $( document ).ajaxComplete(function() {

    some_function();

  });
})

回答by Murali Murugesan

I would suggest the below

我会建议以下

 jQuery(document).ready(InitializeSettings);

also call the same in ajax calls

在ajax调用中也调用相同的

  ajax_success_function(){ // depends on your ajax call
   InitializeSettings();
  }


  function InitializeSettings(){

    if( $('.img-frame a').length > 0 ){
       var myPhotoSwipe = $(".img-frame a").photoSwipe();
     }
  }

回答by Panagiotis Palladinos

Like Morpheus said.

就像墨菲斯说的那样。

Create a seperate function that put your code in that.

创建一个单独的函数,将您的代码放入其中。

You can call that function inside your $(document).ready()

您可以在您的内部调用该函数 $(document).ready()

Then use that same function in your ajax success path (check documentation: http://api.jquery.com/jQuery.ajax/).

然后在您的 ajax 成功路径中使用相同的函数(检查文档:http: //api.jquery.com/jQuery.ajax/)。

Alternatively you can use this: http://api.jquery.com/ajaxStop/

或者你可以使用这个:http: //api.jquery.com/ajaxStop/

It will facilitate you to use the same function when your every Ajax Call stops.

当您的每个 Ajax 调用停止时,它将方便您使用相同的功能。