问题
I understand that using the same id multiple times in a page creates malformed html. When using a jquery selector only the first element with the id will be returned, but in my application I shouldn't be running into this issue.
I have list of items views that will all have an element I need to refer to. Since each item only has access to its own $el
passing in an id selector for something will not produce any conflicts (even if there are multiple on the page).
I've simulated what I mean in a fiddle here
In this project I am not doing any page wide parses so I believe it should be safe. Is there any reason why I should not be doing this?
回答1:
You only know what the current requirements are.
It is best to keep to standards and to valid code/markup as you don't know what will happen in the future.
In this application, you may very well end up having to use jQuery and then you will be in trouble.
The solution for styling multiple elements the same way is to use CSS classes - there is absolutely no reason not to do so, as it is just as simple as using ids.
回答2:
http://www.w3.org/TR/WCAG20-TECHS/H93.html
http://www.w3.org/TR/html401/struct/global.html#adef-id
There are other things that read your HTML document, not just browsers.
According to the HTML specification, the id attribute MUST be unique on a page (it's not a criteria web designers/developers just invented)
回答3:
Absolutely. The specs for HTML, CSS, and JavaScript are an agreement as to how a browser will behave when confronted with certain code. Browsers don't make many guarantees when you do anything that's off-spec, and they make even fewer that they would all agree on.
As Oded mentioned in his comment on the question, browsers build a DOM tree from your code, style it, and render it. So, depending on how a given browser decided to do that, they may run into problems with multiple elements with the same id.
So, why risk it? I can't think of any instance where a class (or nothing at all) couldn't be used in place of an id.
回答4:
yes it is bad practice. An id
should be a unique reference to that element. Use class
instead.
来源:https://stackoverflow.com/questions/14446022/is-using-the-same-id-multiple-times-on-a-page-bad-practice-even-when-i-am-not-pa