javascript - 在可重用 Polymer 组件内的元素上使用 ID 是否安全?

标签 javascript dom polymer polymer-1.0

Polymer 0.5 FAQ 对此声明如下:

My components are producing markup with multiple ids of the same name.

The Shadow DOM polyfill tries hard to mimic native Shadow DOM, in that nodes with the same ids will still be encapsulated.

However, you should avoid using DOM-level id referencing (e.g. <label for>) when using the polyfill. The id may not resolve correctly when under the Shadow DOM polyfill.

在 Polymer 1.x 中这仍然适用吗?如果我执行 document.getElementById,那不会总是返回 DOM 中具有该 ID 的第一个元素吗?如果重用 Polymer 组件,我是否需要先将我的范围限制在感兴趣的组件,然后调用 component.getElementById(或 Polymer 的 component.$.ID)?

这当然对通过测试框架访问元素也有影响。另一种方法是使用类来访问组件中的元素(例如 component.$$('.myClass')),但使用 ID 似乎更简洁并且通常更合适。对此的更多说明将不胜感激。

最佳答案

在同一页面上多次使用一个 ID 永远不会“安全”。任何可重用的组件都应该始终使用类。您已经确定了这样做有风险的许多原因 - 但还请记住,当您有多个实例使用相同的 ID 名称时,您将无法使用基本的 JS 函数,如 getElementByID() 。

关于javascript - 在可重用 Polymer 组件内的元素上使用 ID 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309661/

相关文章:

javascript - 将函数添加到 $(this) 的原型(prototype)

javascript - masonry 图像不垂直堆叠

javascript - 通过 Javascript 获取/设置 CSS 属性值 : questions

javascript - polymer 纸标签选择未按预期工作

javascript - 焦点轮廓在右侧断开 - 未完全包裹元素

javascript - 如何使用js查询Polymer中的shadow dom元素?

javascript - Jquery 验证不起作用

javascript - JQuery 滚动列表框模仿与键盘导航?

Javascript意外的意外标识符

Jquery如何向dom添加元素