【问题标题】:Run jquery function again after ajax callajax调用后再次运行jquery函数
【发布时间】:2014-06-03 16:15:02
【问题描述】:

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

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

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

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

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

     }
});

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

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

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

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;
    });
});

我在 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');

【问题讨论】:

  • 你的ajax调用怎么样?
  • 将您的代码移动到函数中并在 $(document).ready() 和 ajax 请求之后调用该函数
  • 我已经用所有相关代码编辑了问题

标签: javascript jquery ajax run-script


【解决方案1】:

把它放在一个函数中,在页面加载和你的 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();
});

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

还有你的负载调用:

$('.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();
            }
        );

【讨论】:

  • 好的,谢谢,我明白逻辑了。但是,我必须为“URL:”设置什么?
  • 是的,我错过了。好的,我快到了,它只有在我复制 ajax-load-more.js 中的完整功能时才有效,否则我会得到 setMyPhotoSwipe();没有定义。 (第一个 photoswipe 调用它在另一个 js 文件中)。但是,如果我复制该函数,我会收到此错误 Uncaught Code.PhotoSwipe.activateInstance: Uncaught Code.PhotoSwipe.activateInstance: Uncaught Code.PhotoSwipe.activateInstance: Unable to active instance,因为另一个实例已经为此目标活动。尽管一切正常,但我不认为它很“优雅”
  • (对不起,我试图更好地格式化我的评论,但我用完了 5 分钟的时间)
  • 那么你必须标记那些之前已经加载的链接,我更新了我的答案,见函数setPhotoSwipe()。关于您的错误:将函数定义放在jQuery(document).ready之外。
  • 我只是这样设置函数:$.fn.setMyPs = function()... 并像你在我的 ajax 调用中所说的那样运行它,现在一切工作完美无误。非常感谢@Simon 和大家。
【解决方案2】:

插件没有委托,由作者的插件来合并它。为什么不作弊:(对不起,无法测试代码并且不确定它是否与 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();
          }
    });

});

【讨论】:

  • 嘿,不用mousedown,我们不能用mousemove吗? @roasted 我想知道!
  • 我不知道这个插件,但我相信你可以试试
  • 顺便说一句,你的回答太棒了!和我这边的 +1 :) 我也没有尝试过,但我认为它是正确的!
【解决方案3】:
$.ajax({
    url: 'url/test.php',
    success: function(data) { // also gets response from php and can be manipulated if required!
        setMyPhotoSwipe();
    }
});

【讨论】:

  • 这是@Simon 的回答,但多了一项回调功能!
【解决方案4】:

我建议如下

 jQuery(document).ready(InitializeSettings);

在 ajax 调用中也同样调用

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


  function InitializeSettings(){

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

【讨论】:

    【解决方案5】:

    就像墨菲斯所说的那样。

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

    您可以在 $(document).ready() 中调用该函数

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

    您也可以使用这个:http://api.jquery.com/ajaxStop/

    它会方便你在每次 Ajax 调用停止时使用相同的功能。

    【讨论】:

      【解决方案6】:

      对不起,我是 jquery 的新手......使用 ajaxComplete() 怎么样

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

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

      $(document).ready(function(){
      
        function some_function()
        {
        //---- this function to be called after ajax request...
        }
      
        $( document ).ajaxComplete(function() {
      
          some_function();
      
        });
      })
      

      【讨论】:

      • 谢谢!安装 Ajax Load More Posts WP Plugin 后,jquery 插件初始化函数对 WP 插件调用 ajax 后正在加载的帖子图像不起作用,所以我使用了这个函数在我的带有 wp 常量的页面模板上仅在我的自定义帖子类型页面模板上加载该函数并且它有效。
      猜你喜欢
      • 2012-10-19
      • 2014-05-06
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多