Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

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

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 examples of when and when not to escape selectors. So when and when don't I need to escape metacharacters, when they are to be interpreted as a literal, in:

Attribute selectors? ie

$("[attr=value]")

Id selectors? ie

$("#id")

Class selectors? ie

$(".class");

And, is there a way to write a function that replaces metachars in selector strings, while still preserving the beginning character? ie:

// replace all meta chars, preserving the id selection?
$("#id.rest$of*string")

// replace all meta chars, preserving the attribute selection?
// going back to my previous question, do I even need to escape the metachars in this situation?
$("[attr=blah.dee#foo*yay]")

The reason I ask this question, is because I'm working with a website that happens to have some really nasty selectors. And I don't have control over the website, so I can't go change the selectors to be nicer to work with.

THANKS!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...