jQuery .each() over .wp-caption

怎甘沉沦 提交于 2019-12-22 12:32:04

问题


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.



来源:https://stackoverflow.com/questions/6720310/jquery-each-over-wp-caption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!