命名约定 - JS 中的 HTML 元素
如何在 JS 中命名 HTML 元素对象?
var divEditorArea = document.getElementById("editorarea");
var btnCheckSyntax = document.getElementById("checksyntax");
这是一个好方法吗?
How do I name the HTML element objects in JS?
var divEditorArea = document.getElementById("editorarea");
var btnCheckSyntax = document.getElementById("checksyntax");
Is this a good way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,JS 中没有命名 HTML 元素的约定。 Javascript 是一个如此多样化的世界,即使有一个约定,也很难被社区的大多数人遵循。例如,请参阅各种代码 linter 和代码样式约定 (https: //www.sitepoint.com/comparison-javascript-linting-tools/)。
名称应该清楚地表明您的意图,以便代码易于理解。我认为将 HTML 元素的类型添加到 JS 变量名称对于清晰起见(示例中的“btn”和“div”)没有多大用处,但在某些情况下它可能会增加清晰度。而且,如果您在一个团队中,您可能应该遵守团队的惯例。
运用您的最佳判断并始终努力使代码清晰。
To my knowledge, there is no convention for naming HTML elements in JS. Javascript is such a diverse world that even if there was a convention, it would hardly be followed by the majority of the community. See, for example, the variety of code linters and code style conventions there are (https://www.sitepoint.com/comparison-javascript-linting-tools/).
Names should show your intentions clearly, so that code is easily understandable. I don't think that adding the type of the HTML element to the JS variable names is of much use for clarity purposes (the 'btn' and 'div' in you example), but there could be cases where it adds clarity. And, if you are in a team, you probably should follow the team's conventions.
Use your best judgement and always strive for clarity in your code.
如果您使用普通 JS,正如 Vinicius 所说,没有为 HTML DOM 元素命名 JS 变量的约定。
我将它们命名为:
另一种方法是一些团队喜欢在 DOM 元素上添加 $ 前缀。因此,一旦团队中的任何人看到任何以 $ 为前缀的变量,他们就知道它是一个 DOM 元素。
像这样
,这完全取决于你是否独立工作的便利性以及你的团队的命名约定
If you use vanilla JS, as Vinicius told there is no convention for naming JS variables for HTML DOM elements.
I would name them as:
another way would be some team like to prefix the DOM elements with $. So as soon as anybody in the team sees any variable prefixed with $ they know it's a DOM element.
like this
so, it totally depends on your convenient if you work independently and your team's naming convention