I’ve tried to use one of my own jQuery plugins—that I know works—only to receive the following console messages without any reference to a code line number, hence no way to track down the culprit:
uncaught exception: Syntax error, unrecognized expression: #
I’m sure this has caught me out a number of times. Each time is far enough apart that I have forgotten how I debugged the issue previously. And each time I search the interwebs in vain. No one seems to have clearly explained what causes this exception!
Next time I encounter this problem, hopefully I remember—or find—this post, solution follows…
Solution
This exception is thrown by jQuery when you ask it to resolve the selector '#'
without an id
following. In my case it is often caused by my plugin code assuming an element has an id
. If the element doesn’t have an id
, the exception is thrown, for example:
...
var storedID = $(this).attr('id');
...
$('#'+storedID).doSomething();
...
When this
doesn’t have an id
, I’ve essentially asked jQuery to resolve the following:
...
$('#').doSomething();
...
Which jQuery doesn’t like to do, hence the exception.
By Ben Boyle November 17, 2010 - 9:21 pm
That’s why I generate @id when needed—got a little jquery function that will:
– use the existing @id, if there is one
– assign and use a suggested id, if nothing else is using it already
– generate a new id.
Check out forces_id(suggestedId) here:
http://code.google.com/p/usetheforces/source/browse/trunk/src/jquery/forces/dom.js
By Andrew Ramsden November 17, 2010 - 9:50 pm
Very nice! I’ll use that in future, thanks đŸ™‚