【问题标题】:Add same class to multiple Objects将同一类添加到多个对象
【发布时间】:2019-02-05 10:45:55
【问题描述】:

我需要使用 jQuery 为多个对象添加一个类名。

我知道像这样向多个选择器添加一个类:

$("#Div4 ,#Div5 ,#Div7 ,#Div8").addClass("something");

我尝试了以下代码,但它仅将类应用于第一个对象。

$(a[i].source, a[i].canvas, a[i].target).addClass("something");

在上述情况下,类名something 仅应用于a[i].source

想法?

【问题讨论】:

  • $(a[i].source + ', ' + a[i].canvas + ', ' + a[i].target), 在您的语句中被视为参数之间的分隔符。使用+ 连接它们。
  • @Tushar 仅当a[i].source 等实际返回可以解析为选择器的字符串时才有效。如果它是一个节点/元素,这将不起作用。

标签: javascript jquery html jsplumb


【解决方案1】:

假设a[i].source等实际引用了一个Node/Element,则可以使用.add() to add them individually to a collection,即:

$(a[i].source).add(a[i].canvas).add(a[i].target).addClass('something');

这可能是不必要的冗长。您可以简单地构造一个数组并依赖 jQuery (credit to @Rory) 中的隐式迭代:

$([a[i].source, a[i].canvas, a[i].target]).addClass('something');

但是,这并不是真正需要的。只使用原生 JS 怎么样? Array.prototype.forEach()Element.classList 目前已得到广泛支持:

ES6:

[a[i].source, a[i].canvas, a[i].target].forEach(el => el.classList.add('something'));

ES5(如果您需要向后兼容不支持 ES6 语法的浏览器):

[a[i].source, a[i].canvas, a[i].target].forEach(function(el) {
    el.classList.add('something');
});

【讨论】:

    【解决方案2】:

    与其尝试通过 id 获取它们,不如为您需要抓取的元素添加一个默认类。

    <div class="selectorClass"></div>
    <span class="selectorClass"></span>
    

    那么 使用 jquery

    $(".selectorClass").addClass("something")
    

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 1970-01-01
      • 2012-03-16
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2017-10-22
      • 1970-01-01
      相关资源
      最近更新 更多