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
383 views
in Technique[技术] by (71.8m points)

javascript - Jquery Syntax error, unrecognized expression:

Why do I get this error and how can I test for it so it wont break, I tried checking for null but obviously that wont work, thanks.

Please don't advice to not write the ID like this as I know its wrong but it is a possibility.

var jsonTest = [
  {
    "myId": "''''''""""'''''''''''''"#####$'''''",
  }
];

alert(jsonTest[0].myId); 
// Works - alerts the myId

$('#' + jsonTest[0].myId ).length; 
// Error: Syntax error, unrecognized expression:
// #''''''""""'''''''''''''"#####$'''''
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

jQuery's uses this code to detect an id based selector :

characterEncoding = "(?:\\.|[\w-]|[^\x00-\xa0])+"
...
"ID": new RegExp( "^#(" + characterEncoding + ")" ),

This regex fails for "''''''""""'''''''''''''"#####$'''''" or more simply for "'".

The query engine is limited, which isn't very surprising for a so concise language and id validity rules so lax. it can't handle any valid id.

If you really need to be able to handle any kind of valid id, use

$(document.getElementById(jsonTest[0].myId))

In fact, you should never use $('#'+id) as it simply adds a useless (and a little dangerous) layer of parsing for the same operation.


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

...