A convention for indicating whether an HTML elemen

2019-09-11 09:50发布

问题:

This is a follow-up question for In jQuery is it a bad idea to use name=X for all selectors?


I am using Backbone and decided that I wanted a way to differentiate between HTML elements that were bound and those that were not.

So I would write (in HAML):

.container
  .title(name='title')
  .separator  

As you can see it's clear that the dynamic element is title.

The reason for this was so I could mess around with the style and rename classes without worrying about breaking the app. It also means in the template I can tell what the dynamic elements are without needing to go back and forth with the Backbone View.

My question now is, without using the [name] selector, does anyone have a code convention to keep track of which HTML elements are referenced from JS.

I have considering:

  • Using a common prefix on class names (e.g. class=bind-title)
  • Using some sort of custom HTML element (

Thanks!


FYI: I'm using CoffeeScript, Backbone and haml_coffee templates.


Updated jsperf to test all suggestions:

http://jsperf.com/class-or-name-attr-lookup/3

回答1:

I would consider using a class to indicate that it is dynamic. I'm not sure if you are aware of this but you can have multiple classes on one element. Like so:

.container
  .dynamic.title(name='title')
  .separator  

This works in traditional HAML but I have not tried it with haml-coffee. If it doesn't work, you might have to specify the class like .title{:class => "dynamic"}(name='title').

I prefer this over a prefix on the class name because it's more semantically meaningful, which is how HTML should be used.



回答2:

I am using data-view attribute on elements being set when rendering my Views.

This helps me to then show a tooltip in a browser window when I hover over View(s).