Javascript 和 CSS,使用破折号

发布于 2024-08-19 08:50:51 字数 232 浏览 8 评论 0原文

我开始学习一些 javascript 并了解命名标识符时不允许使用破折号。然而,在 CSS 中,通常使用破折号来表示 ID 和类。

在 CSS 中使用破折号是否会以某种方式干扰 javascript 交互?例如,如果我要使用 getElementByID("css-dash-name")。我尝试了一些使用 getElementByID 和破折号作为 div ID 名称的示例,并且它有效,但我不确定在所有其他上下文中是否都是这种情况。

I'm starting to learn some javascript and understand that dashes are not permitted when naming identifiers. However, in CSS it's common to use a dash for IDs and classes.

Does using a dash in CSS interfere with javascript interaction somehow? For instance if I were to use getElementByID("css-dash-name"). I've tried a few examples using getElementByID with dashes as a name for a div ID and it worked, but I'm not sure if that's the case in all other contexts.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

忆悲凉 2024-08-26 08:50:51

在 ID(或类名称,如果您选择的话)中使用破折号和下划线不会产生任何负面影响,可以安全地使用它们。您只是不能执行以下操作:

var some-element = document.getElementByID('css-dash-name');

上面的示例将会出错,因为您要为其分配元素的变量中有破折号。

不过,由于变量不包含破折号,因此以下内容就可以了:

var someElement = document.getElementByID('css-dash-name');

JavaScript 变量本身仅存在命名限制。

Having dashes and underscores in the ID (or class name if you select by that) that won't have any negative effect, it's safe to use them. You just can't do something like:

var some-element = document.getElementByID('css-dash-name');

The above example is going to error out because there is a dash in the variable you're assigning the element to.

The following would be fine though since the variable doesn't contain a dash:

var someElement = document.getElementByID('css-dash-name');

That naming limitation only exists for the javascript variables themselves.

羞稚 2024-08-26 08:50:51

只有在您可以将元素作为属性访问的情况下,它才会产生影响。例如表单字段:

<form>
   <input type="text" name="go-figure" />
   <input type="button" value="Eat me!" onclick="...">
</form>

在 onclick 事件中,您无法将文本框作为属性访问,因为破折号在 Javascript 中被解释为减号:

onclick="this.form.go-figure.value='Ouch!';"

但您仍然可以使用字符串访问它:

onclick="this.form['go-figure'].value='Ouch!';"

It's only in the cases where you can access the elements as properties that it makes a difference. For example form fields:

<form>
   <input type="text" name="go-figure" />
   <input type="button" value="Eat me!" onclick="...">
</form>

In the onclick event you can't access the text box as a property, as the dash is interpreted as minus in Javascript:

onclick="this.form.go-figure.value='Ouch!';"

But you can still access it using a string:

onclick="this.form['go-figure'].value='Ouch!';"
愚人国度 2024-08-26 08:50:51

每当您必须将 CSS 属性作为 JavaScript 变量名称时,CamelCase 就是官方的选择。

element.style.backgroundColor = "#FFFFFF";

您永远不会遇到必须将元素的 ID 作为变量名进行寻址的情况。它总是在一个字符串中,所以

document.getElementById("my-id");

总是有效。

Whenever you have to address a CSS property as a JavaScript variable name, CamelCase is the official way to go.

element.style.backgroundColor = "#FFFFFF";

You will never be in the situation to have to address a element's ID as a variable name. It will always be in a string, so

document.getElementById("my-id");

will always work.

画中仙 2024-08-26 08:50:51

使用连字符(或破折号)就可以

我目前也在学习 JavaScript,据我读过 David Flanagan 的书(JavaScript:权威指南,第五版)——我建议你阅读它。它不会警告我有关在 HTML 文档中的 ID 和类(甚至是 Name 属性)中使用连字符或破折号 (-) 的任何信息。

正如 Parrots 所说,变量中不允许使用连字符,因为 JavaScript 解释器会将其视为减号和/或负号;但如果用在字符串上,就完全没问题了。

就像 Parrots 和 Guffa 所说的,你可以使用以下...

  1. [ ] (方括号)
  2. '' (单引号或单引号)
  3. "" (双引号或双引号)

    告诉 JavaScript 解释器您正在声明字符串(例如元素的 id/类/名称)

使用连字符(或破折号)——为了“一致性”

@KP,如果他使用的是 HTML 4.1 或更早版本,那就没问题,但如果他使用的是任何版本的 XHTML(例如,XHTML 1.0) ,那么这是不可能的,因为 XHTML 语法禁止大写(除了!DOCTYPE,这是唯一需要用大写声明的东西)。

@Choy,如果您使用的是 HTML 4.1 或更早版本,那么使用 CamelCase 或 PascalCase 都不会成为问题。不过,为了保持 CSS 如何使用分隔符(使用连字符或破折号)的一致性,我建议遵循其规则。您可以更方便地编写 HTML 和 CSS 代码。而且,您甚至不必担心您使用的是 XHTML 还是 HTML。

Using Hypen (or dash) is OK

I too is currently studying JavaScript, and as far as I read David Flanagan's book (JavaScript: The Definitive Guide, 5th Edition) — I suggest you read it. It doesn't warn me anything about the use of hypen or dash (-) in IDs and Classes (even the Name attribute) in an HTML document.

Just as what Parrots already said, hypens are not allowed in variables, because the JavaScript interpreter will treat it as a minus and/or a negative sign; but to use it on strings, is pretty much ok.

Like what Parrots and Guffa said, you can use the following ...

  1. [ ] (square brackets)
  2. '' (single quotation marks or single quotes)
  3. "" (double quotation marks or double quotes)

    to tell the JavaScript interpreter that your are declaring strings (the id/class/name of your elements for instance).

Use Hyphen (or dash) — for 'Consistency'

@KP, that would be ok if he is using HTML 4.1 or earlier, but if he is using any versions of XHTML (.e.g., XHTML 1.0), then that cannot be possible, because XHTML syntax prohibits uppercase (except the !DOCTYPE, which is the only thing that needs to declared in uppercase).

@Choy, if you're using HTML 4.1 or earlier, going to either camelCase or PascalCase will not be a problem. Although, for consistency's sake as to how CSS use separators (it uses hypen or dash), I suggest following its rule. It will be much more convinient for you to code your HTML and CSS alike. And moreoever, you don't even have to worry if you're using XHTML or HTML.

奶气 2024-08-26 08:50:51

ID 允许包含连字符

  • IDNAME 令牌必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0- 9])、连字符(“-”)、下划线(“_”)、冒号(“:”)和句点(“.”)。

在 JavaScript 中使用 ID 时没有任何限制,除非您想引用全局范围内的元素。在那里你需要使用:

window['css-dash-name']

IDs are allowed to contain hyphens:

  • ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

And there is no restriction when using IDs in JavaScript except if you want to refer to elements in the global scope. There you need to use:

window['css-dash-name']
错爱 2024-08-26 08:50:51

在这种情况下会导致错误:

const fontSize = element.style.font-size;

因为包含连字符会阻止通过点运算符访问该属性。 JavaScript 解析器会将连字符视为减法运算符。正确的方法是:

const fontSize = element.style['font-size']

It would cause an error in this case:

const fontSize = element.style.font-size;

Because including a hyphen prevents the property from being accessed via the dot operator. The JavaScript parser would see the hyphen as a subtraction operator. Correct way would be:

const fontSize = element.style['font-size']
浮生未歇 2024-08-26 08:50:51

至于可以和不能使用连字符的其他答案是正确的,但是从问题的根源来看,您应该考虑在变量/类/ID 名称中不使用破折号/连字符的想法。这不是标准做法,即使它确实有效并且需要仔细编码才能使用它。

考虑使用 PascalCase(所有单词以大写开头)或 CamelCase(第一个单词以小写字母开头,后面的单词以大写字母开头)。这是两种最常见、公认的命名约定。

不同的资源会在两者之间推荐不同的选择(JavaScript 除外,它几乎总是推荐驼峰命名法)。最后,只要你的方法保持一致,这就是最重要的部分。使用驼峰式或帕斯卡式大小写将确保您不必担心代码中的特殊访问器或括号。

对于 JavaScript 约定,请尝试这个问题/讨论:

javascript 命名约定

这是关于 CSS 约定的另一个精彩讨论, Html 元素等:

什么是最好的如何在 CSS 和 HTML 中命名 ID 和类?

Other answers are correct as far as where you can and can't use hyphens, however at the root of the question, you should consider the idea of not using dashes/hyphens in your variable/class/ID names altogether. It's not standard practice, even if it does work and requires careful coding to make use of it.

Consider using either PascalCase (all words begin in capital) or camelCase (first word begins in lowercase, following words being in uppercase). These are the two most common, accepted naming conventions.

Different resources will recommend different choices between the two (with the exception of JavaScript which is pretty much always recommended camelCase). In the end as long as you are consistent in your approach, this is the most important part. Using camel or Pascal case will ensure you don't have to worry about special accessors or brackets in your code.

For JavaScript conventions, try this question/discussion:

javascript naming conventions

Here's another great discussion of conventions for CSS, Html elements, etc:

What's the best way to name IDs and classes in CSS and HTML?

妞丶爷亲个 2024-08-26 08:50:51

不,这不会引起问题。您以字符串形式访问 ID(用引号引起来),因此破折号不会造成任何问题。但是,我建议不要使用 document.getElementById("css-dash-name"),而是使用 jQuery ,所以你可以这样做:

$("#css-dash-name");

这更清楚。 jQuery 文档也相当不错。它是网络开发人员最好的朋友。

No, this won't cause an issue. You're accessing the ID as a string (it's enclosed in quotes), so the dash poses no problem. However, I would suggest not using document.getElementById("css-dash-name"), and instead using jQuery, so you can do:

$("#css-dash-name");

Which is much clearer. the jQuery documentation is also quite good. It's a web developers best friend.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文