Is using the same id multiple times on a page bad practice even when I am not parsing through the page?

人走茶凉 提交于 2019-12-01 15:19:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!