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

时间:2022-10-16 00:31:16

I have had this problem for some time and it's really bugging me.

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

I'm using two wordpress plugin, one for ajax load more and the other for ajax read more. you can see them in the links below:

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

they both are working fine, but "Read More" does not work in the posts generated by "Load More". here's the jQuery code in "Read More" which i think should be edited:

它们都工作正常,但“阅读更多”在“加载更多”生成的帖子中不起作用。这里是“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: I have used .live, .on and .delegate and they did non work.

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

Edit: and This is the "Load More" code. any idea how to trigger the "Read More" through this?

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

jQuery(document).ready(function() {

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

});

});

4 个解决方案

#1


2  

Use .on() jQuery method.

使用.on()jQuery方法。

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

.on() allow to add events on dynamically loaded content.

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

#2


1  

For actions on future elements, you should use jQuery on.

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

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

Note that it is different from $(post.moreLink).on('click',function(){.....}); which will not affect future elements. Also, make sure that your variable post.moreLink is set.

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

#3


1  

I dont have the right to comment, so I use an answer and I hope It helps.

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

I think the problem is related to triggering the Jquery action of first plugin after the DOM is updated by second plugin. In other words, you need to call the actions of Readmore plugin in the AJAX function relatif to LoadMore Plugin (after results of LoadMore are returned).

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

I think I have already faced such issue here:

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

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

wordpress插件的jquery脚本不能在通过ajax加载的内容中工作

#4


0  

You can fix this two ways.

你可以解决这两种方式。

Yes one is to use .live method, which if used correctly certainly works.

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

2nd way is to create method for binding events and use this method in ajax callbacks which run after the content has been received and added to document.

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

In your code i can see you are doing stuff on successful data load but nothing indicates that you are actually binding any events to new content

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

#1


2  

Use .on() jQuery method.

使用.on()jQuery方法。

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

.on() allow to add events on dynamically loaded content.

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

#2


1  

For actions on future elements, you should use jQuery on.

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

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

Note that it is different from $(post.moreLink).on('click',function(){.....}); which will not affect future elements. Also, make sure that your variable post.moreLink is set.

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

#3


1  

I dont have the right to comment, so I use an answer and I hope It helps.

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

I think the problem is related to triggering the Jquery action of first plugin after the DOM is updated by second plugin. In other words, you need to call the actions of Readmore plugin in the AJAX function relatif to LoadMore Plugin (after results of LoadMore are returned).

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

I think I have already faced such issue here:

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

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

wordpress插件的jquery脚本不能在通过ajax加载的内容中工作

#4


0  

You can fix this two ways.

你可以解决这两种方式。

Yes one is to use .live method, which if used correctly certainly works.

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

2nd way is to create method for binding events and use this method in ajax callbacks which run after the content has been received and added to document.

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

In your code i can see you are doing stuff on successful data load but nothing indicates that you are actually binding any events to new content

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