Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Syntax error, unrecognized expression for href

When I add below script and run. I am getting this:

Uncaught Error: Syntax error, unrecognized expression: ul li a[href=#!id1]

I am not sure which double quote causing the issue.

HTML

<ul>
 <li class="slist selected" id="id1"><a href="#!id10">Test1/a></li>
 <li class="slist" id="id2"><a href="#!id20">Test2</a></li>
 <li class="slist" id="id3"><a href="#!id30">Test3/a></li>
</ul>

JS

$(document).ready(function () {
    var id = "#!" + window.location.href.split("!")[1];
    if ($("ul li a[href=" + id + "]").length) {
        console.log("present");    
    } else {    
        console.log("absent")
    }
});
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You need to enclose special characters in quotes when using a attribute based selector.

if ($('ul li a[href="' + id + '"]').length) {

Your version of selector would result

if ($("ul li a[href=#!...]").length) {

The #! will throw unrecognized expression.


My version where the "" escape the characters

if ($('ul li a[href="#!..."]').length) {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...