問題描述
我應該如何在 css/js 屬性選擇器 [attr=value]
中轉義屬性?
How should I escape attributes in the css/js attibute selector [attr=value]
?
具體來說,這樣對嗎?
document.querySelector('input[name="test[33]"]')
我正在尋找執行此操作的標準方式"(如果有的話),因為我不希望 Sizzle 使用執行繁重的后備功能
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
推薦答案
是的,這是一種正確的方法.選擇器 3 級規范 聲明如下:
Yes, that is one correct approach. The Selectors Level 3 specification states the following:
屬性值必須是 CSS 標識符或字符串.
Attribute values must be CSS identifiers or strings.
您問題中的示例使用字符串作為屬性值.標識符"定義如下:
The example in your question uses a string as the attribute value. An "identifier" is defined as follows:
在 CSS 中,標識符...只能包含字符 [a-zA-Z0-9] 和 ISO 10646 字符 U+00A0 及更高,加上連字符 (-) 和下劃線 (_);它們不能以數字、兩個連字符或一個連字符后跟一個數字開頭.標識符還可以包含轉義字符和任何 ISO 10646 字符作為數字代碼...
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 (_); 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...
因此,轉義特殊字符并省略引號也是合法的:
So following that, it is also legal to escape the special characters and omit the quotes:
document.querySelector('input[name=test\[33\]]')
這篇關于如何在 css/js 屬性選擇器 [attr=value] 中正確轉義屬性值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!