【发布时间】:2014-06-04 22:18:44
【问题描述】:
我正在尝试从 img 标记中获取以“size-”开头的特定类名,将整个类名存储为变量,然后使用 addClass() 将变量传递给 img 父级 .wp-caption分区。
HTML
<div id="attachment_101" style="width: 470px" class="wp-caption alignleft">
<img class="wp-image-101 size-medium" src="http://192.168.0.8/wp-content/uploads/2014/06/01picAC-460x345.jpg" alt="01picAC" width="460" height="345">
<p class="wp-caption-text">Even though 3-D graphics have been used in the Repair Manual and New Car Features, the 3-D graphics had not been used for technical training.</p>
</div>
jQuery
$('.post img').each(function() {
var imgSize = this.className.match(/\bsize-[^\s]+\b/);
$(this).parent('.wp-caption').addClass(imgSize);
});
我的问题是变量 imgSize 没有被添加为一个类。
我可以让它工作:
$('.post img').each(function() {
var imgSize = this.className.match(/\bsize-[^\s]+\b/);
$(this).parent('.wp-caption').attr('class', imgSize);
});
...但这会删除现有的 align.. 所需的类。
我需要弄清楚如何将“size-[whatever]”变量添加到 .wp-caption div 的类中。
请帮忙 - 我一直在用头撞墙一个小时试图弄清楚这一点。
【问题讨论】:
-
提示:
regex.match()返回一个数组 -
提示2:
console.log(imgSize);