【问题标题】:Use jquery variable to add class to element使用 jquery 变量将类添加到元素
【发布时间】: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);

标签: jquery wordpress


【解决方案1】:

试试:

$('.post img').each(function() {
    var imgSize = this.className.match(/\bsize-[^\s]+\b/)[0];
    $(this).parent('.wp-caption').addClass(imgSize);
});

【讨论】:

  • 有效!你能告诉我加零有什么作用吗?感谢您的超级快速响应。
  • 您的 var imgSize 是 @adeneo 指出的数组。最后的[0] 只是获取数组中的第一个字符串。
猜你喜欢
  • 2013-01-10
  • 2011-03-29
  • 1970-01-01
  • 2012-02-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
相关资源
最近更新 更多