【发布时间】: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