使用 jQuery Nearest() 和 Ajax 注入 HTML

Y坐標

我有一個列表,其中每個項目都可以通過使用 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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章