提问者:小点点

在ajax页面加载更改内容后,无法使每个页面都工作


在页面加载时,我运行这个函数将长引用文章隐藏到可点击的链接中,以防止在我的站点上出现大量评论:

function hide_long_quotes()
{
    $('.comments .comment_quote').each(function(i) 
    {
        var actual_text = $(this).text();
        var content = $(this).outerHTML();

        if(actual_text.length > showChar) 
        {
            var cite = $(this).find('cite span.username').first().text();
            var cite_link = '';

            if (cite.length > 0)
            {
                cite_link = 'from ' + cite;
            }

            var html = '<span class="morecontent">' + content + '</span><a href="" class="morelink">' + moretext + cite_link + '</a><br />';

            $(this).replaceWith(html);
        }
        if (i+1 === quote_count) // this will be executed at the end of the loop
        {
            // deal with being linked to a comment, so we can put the window to the correct scroll position, since it will be different due to hidden quotes making the page smaller
            if(window.location.hash) 
            {
                var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
                if (hash.indexOf("r") >= 0)
                {
                    $('#'+hash)[0].scrollIntoView();
                }
            }
        }
    });
}

问题是,当我通过Ajax/load重新加载“.comments”时,上面的函数不再起作用:

function paginate_comments(page, article_id)
{
    var url = "/includes/ajax/post_comment.php";
    var current_url = window.location.href;
    var host = window.location.host;
    
    if(current_url.indexOf(host + '/admin.php?module=reviewqueue') != -1 || current_url.indexOf(host + '/admin.php?module=articles&view=Submitted') != -1 || current_url.indexOf(host + '/admin.php?module=articles&view=Submitted') != -1)
    {
        var area = 'admin';
    }
    else
    {
        var area = 'normal';
    }
    
    $('.comments').load(url, {'type':'reload', 'article_id': article_id, 'page': page, 'area': area}, function()
    {
        $(".lb-container").show();
        $('.box.comments').get(0).scrollIntoView();
        hide_long_quotes();
    });
}

不确定为什么它不起作用,因为函数是在加载函数的已完成的回调部分中调用的?


共1个答案

匿名用户

将元素集合赋予该函数怎么样:

function hide_long_quotes(var comments = false)
{               /* for the case that you don't pass a collection to the function, maybe in the first call when the page is loaded */
    comments = comments ? comments : $('.comments .comment_quote');
    
    comments.each(function(i) 
    {
...
}

function paginate_comments(page, article_id)
{
...
    $('.comments').load(
        url, 
        {
            'type':'reload', 
            'article_id': article_id, 
            'page': page, 
            'area': area
        }, 
        function() 
        {
            $(".lb-container").show();
            $('.box.comments').get(0).scrollIntoView();
            hide_long_quotes($('.comments .comment_quote'));
        }
    );
}