jQuery .each() over .wp-caption

2019-05-20 09:03发布

问题:

WordPress add an extra 10px to the .wp-caption container when a caption in present. I'm trying to use jQuery to remove the extra 10px. I've been able to do this thanks to the answers in this question, but I realized that b/c there are sometimes multiple images in a post, I need to use something to the effect of .each() to iterate. The code below works for the first image but then wrongly applies the first image's with to the container of the second image. How can I correct the .each() to work properly?

jQuery().ready(function() {
    jQuery(".wp-caption").each(function(n) {
    var width = jQuery(".wp-caption img").width();
    jQuery(".wp-caption").width(width);
    });
    });

Example w/ javascript on

Example w/ javascript off

Update: The most streamlined solution from below:

jQuery().ready(function( $ ) {
    $(".wp-caption").width(function() {
        return $('img', this).width();  
    });
});

Or substituting $ with jQuery to prevent conflicts:

jQuery().ready(function( jQuery ) {
    jQuery(".wp-caption").width(function() {
        return jQuery('img', this).width(); 
    });
});

Both work! =)

回答1:

this is a reference to the current element in the .each().

jQuery().ready(function( $ ) {
    $(".wp-caption").each(function(n) {
        var width = $(this).find("img").width();
        $(this).width(width);
    });
});

...so from this, you use the find()[docs] method to get the descendant <img>, and its width().

You could also pass a function directly to width(), and it will iterate for you.

jQuery().ready(function( $ ) {
    $(".wp-caption").width(function(i,val) {
        return $(this).find("img").width();
    });
});

...here, the return value of the function will be the width set to the current .wp-caption.


EDIT: Updated to use the common $ reference inside the .ready() handler.