语法错误,href的无法识别的表达式

TDG*_*TDG 28 jquery

当我添加下面的脚本并运行时.我得到这个:

未捕获错误:语法错误,无法识别的表达式:ul li a [href =#!id1]

我不确定引起这个问题的双引号.

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>
Run Code Online (Sandbox Code Playgroud)

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")
    }
});
Run Code Online (Sandbox Code Playgroud)

Sha*_*k D 39

使用基于属性的选择器时,需要在引号中包含特殊字符.

if ($('ul li a[href="' + id + '"]').length) {
Run Code Online (Sandbox Code Playgroud)

您的选择器版本将会产生

if ($("ul li a[href=#!...]").length) {
Run Code Online (Sandbox Code Playgroud)

#!会抛出无法识别的表达.


我的版本""逃脱了人物

if ($('ul li a[href="#!..."]').length) {
Run Code Online (Sandbox Code Playgroud)


小智 14

我尝试了提供的解决方案

https://github.com/jquery/jquery/issues/2885
Run Code Online (Sandbox Code Playgroud)

这对我有用.我搜索[href=#] in js and replace with [href*=\\#]

a[href*=\\#]:not([href=\\#])
Run Code Online (Sandbox Code Playgroud)