开发者

Weird jQuery error

I was going along minding my jQuery business, when all of a sudden, I tried to do this:

var myVariable = 'some-id-here';
$('#' + myVariable).addClass('some-class');

Everything went fine and dandy until I closed my browser. After I reopened the page, jQuery threw this weird error:

Uncaught Syntax error, unrecognized expression: #

I was able to replace the second line with this and have it work, but I am curious why the first part开发者_运维问答 didn't work after I closed and reopened my browser.

    $(document.getElementById(myVariable)).addClass('current');


It sounds like when you are defining myVariable, there is a # and the beginning of the id. This will also cause the exact error you are getting when you are using this as your selector -

$('##some-id-here').addClass('some-class');

If this is the issue, it would explain why using this instead does work: $(document.getElementById(myVariable)).addClass('current');

I'm not sure why closing the browser would affect this at all. Maybe you made a change to your html that seemed to only be reflected when you reopened your browser?


$('#') throws "Uncaught Syntax error, unrecognized expression: #" in jQuery. So the problem is almost certainly that myVariable is empty..


If myVariable is not empty this should work without a problem even if the element with that ID does not exist.


Do you use the code somewhere else? Some lines down?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜