原型Js多重选择器

Prototype Js Multiple Selector

本文关键字:选择器 Js 原型      更新时间:2023-09-26

我的css路径:

#product_composite_configure .entry-edit .buttons-set.a-right .scalable

我如何选择这个使用prototype js ?我想给这个项目添加一个新属性。

这行不通:

<script type="text/javascript">
    $$('#product_composite_configure .entry-edit .buttons-set.a-right .scalable').setAttribute("test","test");
</script>

Thx

(更新)

这个也不行:

$$('div#product_composite_configure div.entry-edit div.buttons-set button.scalable').setAttribute("test","test");

$$()选择器返回所选元素的数组。因此,您需要遍历数组或使用内置迭代器invoke()

例如

$$('.css_class').invoke('writeAttribute','checked',true);

或CSS选择器

$$('#product_composite_configure .entry-edit .buttons-set.a-right .scalable').invoke('writeAttribute',"test","test");

我使用writeAttribute()而不是setAttribute(),因为它适用于所有浏览器PrototypeJS支持

还有一些其他的方法可以使这个工作

$('product_composite_configure').down('.entry-edit .buttons-set.a-right .scalable').writeAttribute('test','test');
$$('#product_composite_configure .entry-edit .buttons-set.a-right .scalable')[0].writeAttribute('test','test');

这完全取决于你的HTML结构和你想要的行为。如果您只针对一个元素,那么使用down()的id查找可能会更好。如果你打算在#product_composite_configure元素中有多个子元素,那么使用$$()选择器和invoke()将意味着任何新元素也会受到影响,而无需重写脚本。

为什么要把事情复杂化?试试这个:

var selectors = ["#product_composite_configure",".entry-edit",".buttons-set",".a-right",".scalable"];
selectors.forEach(function(e, i) {
   $$(e).each(function(elem) {
       elem.setAttribute("test","test");
   })
});