使用 jQuery closest() 和 Ajax 注入 HTML

Inject HTML using jQuery closest() and Ajax

我有一个列表,其中每个项目都可以通过注入 Ajax 来显示其内容。

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

        $('.show-content').click(function() {
            
            var post_id = $(this).closest('article').attr('data-post-id');

            // ↓ Works. Target the .content <div> in the single <li>.
            $(this).closest('li').find('.content').prepend('<div class="loader">Loading...</div>'); 
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    'action': 'load_loop_content',
                    'post_id': post_id
                }
            }).done(function(response) {

                // ↓ Does not work, the button stay displayed.
                $(this).hide(); // Hide Button
                // ↓ Work, but hide the button in all <li>.
                // $('.show-content').hide(); // Hide Button

                // ↓ Works only using $('.content').html(response) and has been injected into all <li>.
                $(this).closest('li').find('.loader').hide(); // Hide Loader

                // ↓ Does not work, nothing happens and the message "Loading ..." is still displayed.
                $(this).closest('li').find('.content').html(response); // Inject Content
                // ↓ Works, but inject the post content in all <li>.
                // $('.content').html(response);

            });

        });
        
    });
})(jQuery);

但是使用closest(),它不再起作用了。我把细节放在代码的注释中。

知道问题出在哪里吗?

只需将您的内容存储到一个 const 中,然后再使用它

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

    $('.show-content').click(function() {

        const myButton = $(this);
        var post_id = myButton.closest('article').attr('data-post-id');

        // ↓ Works. Target the .content <div> in the single <li>.
        const myContent = myButton.closest('li').find('.content');
        myContent.prepend('<div class="loader">Loading...</div>'); 
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                'action': 'load_loop_content',
                'post_id': post_id
            }
        }).done(function(response) {

            myButton.hide(); // Hide Button
            myContent.html(response);

        });

    });
    
});
})(jQuery);