jQuery: unrecognized expression
Asked Answered
M

2

8
$(document).ready(function(){

    var page = window.location.hash;
    if(page != ""){
        $('a[href='+ page +']').addclass('selected');
        pageload(page.replace('#/page/', 'pages/?load='));
    }

    $('#top a').click(function(event){  
        $('#top a').removeClass('selected');
        $(this).addClass('selected');

        pageload($(this).attr('href').replace('#/page/', 'pages/?load='));

        event.preventDefault;
    });
});

 

<div id="top">
    <a href="#/page/link">Link</a>
    <a href="#/page/link">Link</a>
    <a href="#/page/link">Link</a>
    <a href="#/page/link">Link</a>
    <a href="#/page/link">Link</a>
</div>

So when i'm trying to do this, and load up a page using the window.location.hash, i get an error in the console saying:

Uncaught Error: Syntax error, unrecognized expression: [href=#/page/link]

How can i make this work?

Mercuri answered 7/2, 2012 at 16:32 Comment(2)
Are you aware that you are not actually calling event.preventDefault function? You should do that as the first thing in your event handler.Mujik
Well print out the $(this).attr('href') part into console.logOhare
B
18

Try this instead:

$('a[href="'+ page +'"]').addClass('selected');

(You need to escape the value of the href – with this, you get a[href="#/page/link"].)

Ballade answered 7/2, 2012 at 16:35 Comment(6)
"Uncaught TypeError: Object [object Object] has no method 'addclass'" this is what i get in return.Mercuri
Ah, the C in addClass needed to be capital, stupid me. Thanks!Mercuri
good call - starting from jQ 1.5 url needs to be wrapped into something, e.g. href="my/url/" -- href=my/url/ will not go through anymoreFinial
$(container+":has(ul)").length how to change that?Xanthic
@JosuaMarcelChrisano: What do you mean?Ballade
i have the line if ($(container+":has(ul)").length === 0){...} in jquery 1.3.2, then got error when i upgrade the jquery to 1.8.2. How to upgrade my code too? the error is "Uncaught Error: Syntax error, unrecognized expression: [object Object]:has(ul)"Xanthic
P
0

Your regular expression doesn't need the speech marks:

replace(#/page/, ...
Petiole answered 7/2, 2012 at 16:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.