jQuery在Ajax生成的内容中不起作用

时间:2013-03-09 07:15:58

标签: jquery ajax wordpress load

我有这个问题已经有一段时间了,这真的让我烦恼。

我正在使用两个wordpress插件,一个用于ajax加载更多,另一个用于ajax读取更多。你可以在下面的链接中看到它们:

它们都工作正常,但“阅读更多”在“加载更多”生成的帖子中不起作用。这里是“Read More”中的jQuery代码,我认为应该对其进行编辑:

var backgroundAction = false;

jQuery.fn.AJAXReadMore = function (options) {
    var $ = jQuery,
        options = $.extend({
            animateSpeed: 'slow',
            errorMessage: "Error.<br/>Try again later.",
            errorClass: "loading-error",
            loadingClass: "loading",
            spacerClass: "loading-spacer",
            loadedClass: "loaded",
            contentElSelector: ".entry-part",
            moreElSelector: ".more-link",
            moreContainerSelector: ".more-link-container",
            onUpdateEvent: "onupdate",
            parentScrollableEl: $("html,body"),
            scroll: true,
            scrollToSelector: ".entry-header",
            scrollLowBound: 0,
            ajaxData: {}
        }, options);

    return this.each(function () {
        var post = {
            data: $.extend(options.ajaxData, {
                'AJAX-mode': '1'
            }),
            moreLink: $(options.moreElSelector, this),
            navigation: $(options.moreContainerSelector, this)
                .add(options.moreElSelector, this),
            content: $(options.contentElSelector, this),
            el: $(this)
        },
        busy = false;
        if (!(post.content.length)) post.content = post.el;

        $(post.moreLink).on('click', function () {

            if (busy) return false;
            var scroll = (options.scroll) && !(backgroundAction);
            busy = true;

            post.scrollTo = $(options.scrollToSelector, post.el);
            if (!(post.scrollTo.length)) post.scrollTo = post.el;

            var newContent = post.content.clone(true)
                .hide()
                .addClass(options.loadingClass)
                .html("")
                .insertAfter(post.content),
                spacerHeight1 = options.parentScrollableEl.scrollTop() + options.parentScrollableEl.height() - newContent.offset().top,
                spacerHeight = (spacerHeight1 > 0) ? spacerHeight1 : 0,
                spacer = newContent.clone()
                    .addClass(options.spacerClass)
                    .addClass(options.loadingClass)
                    .insertBefore(newContent)
                    .animate({
                    height: "0px"
                },
                options.animateSpeed)
                    .show();
            post.navigation.addClass(options.loadingClass);
            if (scroll) {
                if ((post.scrollTo.offset().top - options.parentScrollableEl.scrollTop() > options.scrollLowBound)) {
                    options.parentScrollableEl.animate({
                        scrollTop: post.scrollTo.offset().top + "px"
                    }, options.animateSpeed);
                };
            };
            $.when(
            $.ajax({
                type: "GET",
                url: post.moreLink.attr('href'),
                dataType: "html",
                cache: true,
                data: post.data
            }),
            post.scrollTo,
            options.parentScrollableEl).then(
            /*success:*/
            function (args) {
                /*args: [ data, "success", jqXHR ]*/
                var data = args[0];
                var dataObj;
                var bodyEl = {
                    length: 0
                };
                try {
                    dataObj = $(data);
                    bodyEl = dataObj.find('body');
                } catch (e) {};
                var dt = {
                    url: post.moreLink.attr('href'),
                    referrer: $(location).attr('href')
                };
                var textStatus = args[1];

                if (bodyEl.length) {
                    dt = $.extend(dt, {
                        body: bodyEl.html(),
                        title: dataObj.find('title').text()
                    });
                } else {
                    dt = $.extend(dt, {
                        body: data
                    });
                };

                post.navigation.addClass(options.loadedClass)
                    .removeClass(options.loadingClass);
                newContent.html(dt.body)
                    .show()
                    .removeClass(options.loadingClass)
                    .slideDown(options.animateSpeed)
                    .trigger(options.onUpdateEvent)
                    .trigger('counter.hit', dt);
                spacer.addClass(options.loadedClass)
                    .removeClass(options.loadingClass)
                    .slideUp(options.animateSpeed, function () {
                    $(this).remove();
                });
                busy = false;
            },
            /*error:*/
            function () {
                /*args: [ request, "error", jqXHR ]*/
                var request = args[0],
                    textStatus = args[1];
                newContent.remove();
                post.navigation.addClass(options.errorClass);
                spacer.hide()
                    .addClass(options.errorClass)
                    .removeClass(options.loadingClass)
                    .html(options.errorMessage)
                    .fadeIn(options.animateSpeed)
                    .delay(1000)
                    .fadeOut(options.animateSpeed)
                    .delay(100)
                    .hide(options.animateSpeed, function () {
                    $(this).remove();
                    post.navigation.removeClass(options.loadingClass)
                        .removeClass(options.errorClass);
                });
                busy = false;
            });
            return false;
        });

    });
};

P.S:我使用了.live.on.delegate,他们没有工作。

编辑:这是“加载更多”代码。任何想法如何通过这个触发“阅读更多”?

jQuery(document).ready(function() {

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

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

// The link of the next page of posts.
var nextLink = pbd_alp.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.
    $('#ajaxload')
        .append('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>')
        .append('<p id="pbd-alp-load-posts"><a href="#">Show More</a></p>');

    // Remove the traditional navigation.
    $('.pagination').remove();
}


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

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

        // Show that we're working.
        $(this).text('');
        $(this).append('<img src="http://bluhbluh.com/wp-content/themes/coffebook/img/loader.gif">');

        $('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post',
            function() {
                // Update page number and nextLink.
                pageNum++;
                nextLink = nextLink.replace(/\/page\/\d{0,9}/, '/page/'+ pageNum);

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

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

    return false;
});

// The number of the next page to load (/page/x/). var pageNum = parseInt(pbd_alp.startPage) + 1; // The maximum number of pages the current query can return. var max = parseInt(pbd_alp.maxPages); // The link of the next page of posts. var nextLink = pbd_alp.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. $('#ajaxload') .append('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>') .append('<p id="pbd-alp-load-posts"><a href="#">Show More</a></p>'); // Remove the traditional navigation. $('.pagination').remove(); } /** * Load new posts when the link is clicked. */ $('#pbd-alp-load-posts a').click(function() { // Are there more posts to load? if(pageNum <= max) { // Show that we're working. $(this).text(''); $(this).append('<img src="http://bluhbluh.com/wp-content/themes/coffebook/img/loader.gif">'); $('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post', function() { // Update page number and nextLink. pageNum++; nextLink = nextLink.replace(/\/page\/\d{0,9}/, '/page/'+ pageNum); // Add a new placeholder, for when user clicks again. $('#pbd-alp-load-posts') .before('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>') // Update the button message. if(pageNum <= max) { $('#pbd-alp-load-posts a').text('Show More'); } else { $('#pbd-alp-load-posts a').text('No More Posts'); } } ); } else { $('#pbd-alp-load-posts a').append('.'); } return false; });

4 个答案:

答案 0 :(得分:2)

使用.on() jQuery方法。

$(post.moreLink).on('click',function(){ /**codehere**/ });

.on()允许在动态加载的内容上添加事件。

答案 1 :(得分:1)

对于未来元素的操作,您应该使用jQuery on

$(document).on('click',post.moreLink, function(){ 
// write your codes
});

请注意,它与$(post.moreLink).on('click',function(){.....});不同,后者不会影响将来的元素。另外,请确保已设置变量post.moreLink

答案 2 :(得分:1)

我没有评论的权利,所以我使用答案,我希望它有所帮助。

我认为问题与第二个插件更新DOM后触发第一个插件的Jquery操作有关。换句话说,你需要在AJAX函数中调用Readmore插件的动作来重新加载LoadMore插件(在返回LoadMore的结果之后)。

我想我已经在这里遇到过这样的问题:

jquery script of wordpress plugin dont work in content loaded via ajax

答案 3 :(得分:0)

您可以通过以下两种方式解决此问题。

是的,使用.live方法,如果使用正确,肯定有效。

第二种方法是创建绑定事件的方法,并在ajax回调中使用此方法,这些回调在收到内容并添加到文档后运行。

在你的代码中,我可以看到你在成功加载数据时正在做的事情,但没有任何迹象表明你实际上是将任何事件绑定到新内容