Why can't jQuery 3 identify the '#' ch

2020-01-29 17:54发布

问题:

I just tried switching my application to jQuery 3. I was going through some testing and everything was working as expected, until I came to a piece of my application that used a '#' symbol in a selector. I have a piece of jQuery that looks like this:

var $existingFilter = $container.find('.filterFeedItem[data-component-type=#somefilter]');

Using jQuery 3 I get an error:

jquery-3.0.0.js:1529 Uncaught Error: Syntax error, 
unrecognized expression: .filterFeedItem[data-component-type=#somefilter]

Does anyone know why jQuery can no longer parse selectors containing this symbol?

回答1:

Note, the change apparently took place at version 2.0, as version 2.1.3 returned element using selector

var $existingFilter1 = $container.find('.filterFeedItem[data-component-type=#somefilter]');

jsfiddle https://jsfiddle.net/f8nej922/2/

Though have not been able to locate specific reference to or description of change at jQuery 2.2 and 1.12 Released documentation.

As noted by @BoltClock, change is related to Selector: Remove "#" exception for identifier tokens.


You can esacape # character with \\; quote value at attribute selector; or use $.escapeSelector()

var $existingFilter = $container
                      .find('.filterFeedItem[data-component-type=\\#somefilter]');

var $existingFilter = $container
                      .find('.filterFeedItem[data-component-type="#somefilter"]');

var $existingFilter = $container
                      .find('.filterFeedItem[data-component-type=' 
                       + $.escapeSelector('#somefilter') + ']');

jsfiddle https://jsfiddle.net/f8nej922/4/



回答2:

By jQuery's documentation, the attribute value:

Can be either a valid identifier or a quoted string.

The valid identifier being any valid css identifier:

https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier

In CSS, identifiers (including element names, classes, and IDs in selectors) 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 (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

Since you are wanting to use #, you need to escape or quote the value:

                         //Note the quotes v --------- v
.find('.filterFeedItem[data-component-type="#somefilter"]');