Javascript / HTML:命名时使用id和class [英] Javascript/HTML: Using id vs. class when naming

查看:110
本文介绍了Javascript / HTML:命名时使用id和class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当我添加一段文字时,一个让我绊倒了一下的错误发生了使用其旁边的按钮进行输入;用户会输入一个他们想要添加到列表中的名字,然后点击按钮来实际添加它。



我的问题是:为什么它看起来如此在HTML中,文本字段必须用id =...命名,而按钮必须用class =...命名?

如需更多参考资料,请在我的JavaScript文件中使用textfieldname.value和'click input.buttonname'。 id和class的要求源于我如何使用它们?

解决方案

id属性用于提供一个元素的全局唯一标识符。 class属性用于根据元素的含义,预期用途,与其他元素的关系或应用程序需要的其他类型对元素进行分类或典型化。

通常使用类来识别事物更为灵活,因为可以为多个元素赋予相同的类,并且元素可以具有所需的类。任何单个元素可能只有一个id,并且这些值不能在同一个文档中重复使用。对于这两个属性来说,有明显的用例,其中一个或另一个明显更合适,还有许多其他情况下,它们不太清楚,哪一个可以使用。

这不是一个真正的JavaScript问题,而是一个Web应用程序设计问题。如何标注HTML元素由内容(HTML)的性质,演示文稿的需求(CSS)以及预期行为(JavaScript)决定。

I am starting to learn some Javascript using Meteor and am looking at their examples.

One bug that tripped me up for a bit happened when I was adding a text-field for input with a button next to it; users would type in a name they wanted to add to a list and then click the button to actually add it.

My question is: why does it seem to be the case that in the html, the text field has to be named with id="..." while the button has to be named with class="..."?

For additional reference, in my javascript file, I am using textfieldname.value and 'click input.buttonname'. Does the id vs. class requirement stem from how I'm using them?

解决方案

The "id" attribute is used to supply a globally-unique identifier for an element. The "class" attribute is used to categorize or typify an element according to its meaning, its intended use, its relationship to other elements, or whatever else your application requires.

Usually it's more flexible to use classes to identify things, because more than one element can be given the same class, and an element can have as many classes as are needed. Any single element may only have one "id", and the values must not be re-used in the same document. There are clear use cases for both attributes in which one or the other is obviously more appropriate, and many other cases where it's less clear and for which either could be used.

This isn't really a JavaScript issue so much as a "web application design" issue. How one labels HTML elements is dictated by the nature of the content (HTML), the needs of the presentation (CSS), and the intended behaviors (JavaScript).

这篇关于Javascript / HTML:命名时使用id和class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆