【问题标题】:Prototype Js Multiple Selector原型 Js 多选器
【发布时间】:2017-02-21 07:22:21
【问题描述】:

这是我的 css 路径:

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

如何使用原型 js 选择它?我想为这个项目添加一个新属性。

这不起作用:

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

谢谢

[更新]

这也不起作用:

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

【问题讨论】:

  • 首先,你为什么使用原型?它已经快一年没有提交了……这在 JavaScript 领域已经很长了……
  • 我必须 :( 这不是我的选择
  • @JaredSmith 也许它只是达到了最佳状态,没有什么可改进的? :-P
  • @Bergi 你的意思是像 Common Lisp 规范? :-P

标签: javascript prototypejs


【解决方案1】:

$$() 选择器返回所选元素的数组。所以你需要遍历数组或者使用内置的迭代器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() 一起使用意味着任何新元素都会受到影响,而无需重写脚本。

【讨论】:

  • 感谢您与我们分享此信息 :)
【解决方案2】:

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

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");
   })
});

【讨论】:

  • 我在萤火虫中得到了这个:TypeError: $$(...).setAttribute is not a function var BundleControl = Class.create();
  • console.log(e) 看看e 是什么,顺便说一句我不熟悉原型
猜你喜欢
  • 2012-05-21
  • 1970-01-01
  • 2013-03-04
  • 2011-06-10
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 2012-02-03
  • 2011-06-16
相关资源
最近更新 更多