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

标签 javascript css css-selectors selectors-api

我应该如何转义 css/js 属性选择器 [attr=value] 中的属性?

具体来说,这是正确的吗?

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

我正在寻找执行此操作的“标准方法”(如果有的话),因为我不希望 Sizzle 使用繁重的执行后备函数

最佳答案

是的,这是一种正确的方法。 Selectors Level 3 specification陈述如下:

Attribute values must be CSS identifiers or strings.

您问题中的示例使用字符串作为属性值。 “标识符”定义如下:

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...

因此,转义特殊字符并省略引号也是合法的:

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

关于javascript - 如何正确转义 css/js 属性选择器 [attr=value] 中的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13987979/

相关文章:

css - Bootstrap CSS 行对齐问题

android - 位置 :fixed, 100% 高度和移动滚动

Jquery选择器问题

javascript - 如何为不写入文件的 grunt 插件编写单元测试?

javascript - python mechanize - 提交自定义表单

javascript - PHP 和 JavaScript : Getting file contents with Javascript variable

javascript - 是否有图像映射的替代方案能够更改图像上特定 div 区域的背景颜色?

javascript - 如何在 JS 中使这个数组键动态化

python - 如何使用选择器选择html元素的属性?

jquery - 选择除第一个 N 之外的所有子级 - CSS 选择器