When do I need to escape metacharectars? (jQuery Selectors)

前端 未结 2 1886
闹比i
闹比i 2020-12-20 21:36

According to the jQuery docs, I need to escape metacharacters that occur in my selector strings, when they occur as a literal. However, I couldn\'t find very many specific e

相关标签:
2条回答
  • 2020-12-20 21:56

    Rather than blatantly stealing someone else's answer, I'll point you to it: jQuery selector value escaping, where jQuery's selector parsing method is described in detail.

    The short answer: you may be in trouble since jQuery's selector parser is not 100% standards-complaint. Per the suggestion in the linked answer, you may be able to workaround by calling the regular DOM methods (document.getElementById()), which will work with funny selectors, and then pass the raw DOM element to the jQuery selector.

    $(document.getElementById("id.rest$of*string"));
    
    0 讨论(0)
  • 2020-12-20 22:02

    From the jQuery docs:

    If you wish to use any of the meta-characters (#;&,.+*~':"!^$=>|/ ) as a literal part of a name, you must escape the character with two backslashes ...

    All of these must be escaped:

    1. id
    2. class name
    3. attribute name
    4. attribute value
    5. element name

    The first four are obvious, and here's an example for the fifth. Element names in XML can contain a "." character for instance and still be valid.

    <user.name>John Doe</user.name>
    

    If you had to select all elements of user.name, then that . must be escaped

    $(xml).find("user\\.name");
    
    0 讨论(0)
提交回复
热议问题