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][1], 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][2]
Example w/ [javascript off][3]
**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]: https://stackoverflow.com/questions/6628758/use-jquery-to-change-wp-caption-inline-style-from-img-attribute
[2]: http://dev.airve.com/blogx/2011/07/test-wp-caption-js/
[3]: http://dev.airve.com/blogx/2011/07/test-wp-caption-no-js/
以上就是jQuery .each() over .wp-caption的详细内容,更多请关注web前端其它相关文章!