【问题标题】:How to add id to element if body contains certain class and an element id contains a class如果 body 包含某个类并且元素 id 包含一个类,如何将 id 添加到元素
【发布时间】:2018-04-30 13:03:40
【问题描述】:

以下代码会将“活动”类分配给 id="39" 的元素。如果满足两个条件,就会发生这种情况:1)主体在其类中包含“hotel-stores”-因此主体类可能是hotel-stores、hotel-stores-1、hotel-stores-2、hotel-stores- 3等-和2) id="dropdown-menu" 的元素将包含“active”类。

仍然,代码不起作用。您是否知道错误在哪里,或者为什么此代码不起作用?

if ( ($('body[class*="hotel-stores"]').length > 0)  && ( $( "#dropdown-menu" ).is( ".active" ) ))  {
   var el = document.getElementById("39");
   el.classList.add("active");
}

第二种方式似乎工作得很好,但只有当 body 类是 'hotel-stores' 时:

if (document.body.classList.contains('hotel-stores')) {
    var el = $(document.getElementById("39"));
    el.addClassName("active");
}

【问题讨论】:

  • 只要元素存在并且在代码运行时具有这些类,它就可以工作:jsfiddle.net/ugtv8uL0 请用minimal reproducible example 更新您的问题,以展示问题,最好是 runnable 一个使用堆栈片段([<>] 工具栏按钮;here's how to do one)。
  • 嗨 T.J.我对其进行了测试,并且出现了一个提示:Uncaught TypeError: Cannot read property 'length' of null at hotel-stores;可能这就是它不起作用的问题。如何解决?

标签: javascript magento magento-1.9


【解决方案1】:

在你说过的评论中

未捕获的类型错误:无法在酒店商店读取 null 的属性“长度”

这告诉我,该代码中的 $ 不是 jQuery,如 I assumed,而是其他一些库,可能是 PrototypeJS,因为它是一个 Magento 站点。

如果您加载了 jQuery,只需将所有 $ 更改为 jQuery 即可。

如果你不加载 jQuery,你可以用 PrototypeJS 做同样的事情,只是略有不同,因为 PrototypeJS 不像 jQuery 那样基于集合:

if (document.body.className.indexOf('hotel-stores') !== -1 && $$("#dropdown-menu.active").length) {
   var el = $(document.getElementById("39"));
   el.addClassName("active");
}

【讨论】:

  • 嗨 T.J. Uncaught TypeError 不再可见,但是 id="39" 的元素还没有得到 class="active" ;你有更多提示吗?
  • @Eduardo:works 上面的代码带有 PrototypeJS,所以如果你没有看到添加的类,那么 body 没有相关的类,#dropdown-menu 没有有相关的类,你复制的代码不正确,或者你的页面没有使用 PrototypeJS。
  • 嗨 T.J.我已经更新了代码(第二种方式);这似乎运作良好,但仅当类别为“酒店商店”时;您是否知道调整此“第二种方式”代码的方法,以使任何以“hotel-stores”开头的类也将在代码中被考虑在内?
  • @Eduardo: 无论hotel-stores 出现在元素的类属性中的什么位置,无论是否属于另一个类,document.body.className.indexOf('hotel-stores') !== -1 都肯定为真。
猜你喜欢
  • 2020-02-17
  • 2020-07-27
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
相关资源
最近更新 更多