[英]Javascript in Magento 1.9.3.8. Add id to element if body contains certain class and an element id contains a class
The following code would assign the class "active" to the element with id="39". 以下代码将为id =“ 39”的元素分配“活动”类。 That would happen if two conditions are met: 1) That the body contains "hotel-stores" in its class -so the body class might be hotel-stores, hotel-stores-1, hotel-stores-2, hotel-stores-3, etc.- and 2) that the element with id="dropdown-menu" would contain the class "active".
如果满足两个条件,就会发生这种情况:1)该实体在其类别中包含“酒店商店”-因此该实体类别可能是酒店商店,hotel-stores-1,hotel-stores-2,hotel-stores- 3,等等-和2)id =“ dropdown-menu”的元素将包含“ active”类。
Still, the code does not work. 尽管如此,该代码仍无法正常工作。 Do you have any ideas where the errors is, or why this code does not work?
您对错误在哪里有什么想法,或者为什么这段代码行不通? Any help would be appreciated.
任何帮助,将不胜感激。
if ( ($('body[class*="hotel-stores"]').length > 0) && ( $( "#dropdown-menu" ).is( ".active" ) )) {
var el = document.getElementById("39");
el.classList.add("active");
}
This second way seems to work pretty well, but only when the body class is 'hotel-stores': 第二种方法似乎工作得很好,但是仅当body class是“ hotel-stores”时:
if (document.body.classList.contains('hotel-stores')) {
var el = $(document.getElementById("39"));
el.addClassName("active");
}
In a comment you've said 您在评论中说
Uncaught TypeError: Cannot read property 'length' of null at hotel-stores
未被捕获的TypeError:无法在酒店商店读取null的属性“长度”
That tells me that $
in that code is not jQuery, as I assumed , but some other library, probably PrototypeJS given it's a Magento site. 这告诉我,代码中的
$
不是我假设的 jQuery,而是其他一些库,可能是PrototypeJS,因为它是Magento站点。
If you also have jQuery loaded, just change all of the $
to jQuery
and it should work. 如果您还加载了jQuery,只需将所有
$
更改为jQuery
。
If you aren't also loading jQuery, you can do the same thing with PrototypeJS, just slightly differently because PrototypeJS isn't set-based like jQuery is: 如果您还不加载jQuery,则可以使用PrototypeJS进行相同的操作,只是略有不同,因为PrototypeJS不像jQuery那样是基于集合的:
if (document.body.className.indexOf('hotel-stores') !== -1 && $$("#dropdown-menu.active").length) {
var el = $(document.getElementById("39"));
el.addClassName("active");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.