jQuery .each()over .wp-caption [英] jQuery .each() over .wp-caption

查看:82
本文介绍了jQuery .each()over .wp-caption的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WordPress在当前的标题中为 .wp-caption 容器添加额外的10px。我正在尝试使用jQuery删除额外的10px。由于这个问题,但我意识到b / c有时在帖子中有多个图像,我需要使用某些东西来效果 .each()迭代。下面的代码适用于第一个图像,但后来错误地将第一个图像应用于第二个图像的容器。如何更正 .each()才能正常工作?

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

示例w / javascript on

示例w / javascript off

更新:下面最简化的解决方案:

Update: The most streamlined solution from below:

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

或用<$ c $代替 $ c> jQuery 以防止冲突:

Or substituting $ with jQuery to prevent conflicts:

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

两者都有效! =)

推荐答案

是对当前元素的引用 .each()

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

...所以从这个,你使用 find() [docs ] 获取后代< img> 的方法及其 width()

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

您还可以将函数直接传递给 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();
    });
});

...这里,函数的返回值将是设置为当前<$的宽度c $ c> .wp-caption 。

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

编辑:更新为在 .ready()处理程序中使用常见的 $ 引用。

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

这篇关于jQuery .each()over .wp-caption的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆