What are the common solutions for making clean id space in a SPA?

后端 未结 7 2176
感情败类
感情败类 2021-02-14 05:05

Situation: several developers working remotely on different section/modules of a SPA. As a result they may accidentally introduce HTML elements with the same id. W

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 05:15

    Try to avoid using ID's except where absolutely necessary. When referencing HTML snippets from CSS or JS, stick to classes instead of IDs. Your CSS and JS shouldn't really care (separation of concerns) about the exact structure of the DOM or how many 'foo' elements are on the page... they just want to style or act on whatever 'foo' elements are there which classes are perfectly suitable for.

    You can't avoid ID's entirely though... for example, marking up your HTML to support accessibility will require the use of IDs... but these IDs and references to them will be constrained to the same HTML file (or SPA template) so go ahead and make them verbose/lengthy to avoid conflicts if you feel a conflict is possible with any of them.

    Of course this doesn't totally solve your problem. By focusing on classes you avoid the possibility of generating invalid HTML and everything blowing up but you still have the collaboration problem of making sure people aren't unexpectedly screwing up each other's work by using the same class names. In many cases, you'll actually want the same classes to be used across pages. In cases where you want to ensure there are no conflicts (for example, having common button or typography styles across the site), however, you could wrap each HTML template in something like

    ...
    and then in your CSS/JS selectors, scope the selector to only match within that template: .name-of-this-template .a-class-used-within-the-template.

提交回复
热议问题