简体   繁体   English

如何在css / js属性选择器[attr = value]中正确转义属性值?

[英]How to properly escape attribute values in css/js attribute selector [attr=value]?

How should I escape attributes in the css/js attibute selector [attr=value] ? 我应该如何在css / js attibute选择器[attr=value]转义属性?

Specifically, is this correct? 具体来说,这是正确的吗?

document.querySelector('input[name="test[33]"]')

I'm looking for the "standard way" of doing this, if any, because I don't want Sizzle using a heavy-to-execute fallback function 我正在寻找这样做的“标准方法”,如果有的话,因为我不希望Sizzle使用繁重的执行回退功能

Yes, that is one correct approach. 是的,这是一种正确的方法。 The Selectors Level 3 specification states the following: 选择器级别3规范声明如下:

Attribute values must be CSS identifiers or strings. 属性值必须是CSS标识符或字符串。

The example in your question uses a string as the attribute value. 您的问题中的示例使用字符串作为属性值。 An "identifier" is defined as follows: “标识符”定义如下:

In CSS, identifiers... can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); 在CSS中,标识符...只能包含字符[a-zA-Z0-9]和ISO 10646字符U + 00A0及更高,加上连字符( - )和下划线(_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. 它们不能以数字,两个连字符或连字符后跟数字开头。 Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code... 标识符还可以包含转义字符和任何ISO 10646字符作为数字代码...

So following that, it is also legal to escape the special characters and omit the quotes: 所以在那之后,逃避特殊字符并省略引号也是合法的:

document.querySelector('input[name=test\\[33\\]]')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM