2

The answer to question Cascading style sheets use "id" or "class" says for id's

Put an ID on an element if "it is the ..." (e.g. navigation)

and a further comment:

Because of this ids can only be used once (in the page) but elements can be classified multiple times. Also an element can only have one identifier but multiple classifications. However elements can be identified and classified.

With shadow dom, does the part about ids can be used once (in the page) still hold? For example, a simple way to grab elements in the component is to give each id's unique to the component and query them:

In html:

<input id="amount" placeholder="Amount" on-change="{{recalc}}"></input>
<input id="term-years" placeholder="Term (yrs) e.g. 30" on-change="{{recalc}}"></input>
<input id="rate" placeholder="Interest Rate" on-change="{{recalc}}"></input>

In Dart code:

termYearsElm = shadowRoot.querySelector('#term-years');
amountElm = shadowRoot.querySelector('#amount');
rateElm = shadowRoot.querySelector('#rate');

In playing with this, multiple instances of the component do not conflict. Is this approach safe or a bad idea? If it is safe then have the rules for ids have changed?

4

1 回答 1

5

是的,在组件的元素上使用 ID 是完全合法的,只要它是 1) 该组件唯一的,并且 2) 该组件具有 shadowDOM。shadowDOM 将您的组件相互封装。因此,您可以拥有一个带有 id 的组件,rate并且它在该组件中只使用一次。即使您在同一页面中多次使用该组件,id 也会相互封装。

也只是一个快速的 FYI,您还可以使用$[]访问器来缩短表单。飞镖代码:

termYearsElm = $['term-years'];
amountElm = $['amount'];
rateElm = $['rate'];
于 2013-11-20T13:54:52.783 回答