不选择器和哈希符号语法错误

jQuery :not selector and hash symbol syntax error

本文关键字:语法 错误 符号 哈希 选择器      更新时间:2023-09-26

我得到一个可爱的语法错误。这是当我尝试选择所有锚标记没有一个包含占位符URL的href,即href="#" .

我试过以下方法:

$("a:not(href='#')");
//swapped single with double quotes
$('a:not(href="#")');
// no quotes at all
$("a:not(href=#)");
// wildcard selector
$("a:not(href*=#)");

所有这些都导致以下错误:

未捕获错误:语法错误,无法识别的表达式:href=#(…)

任何想法?


代码片段如下:

var $item = $("a:not(href='#')");
console.log($item);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.com">Selected</a>
<a href="#">Not selected</a>

href的测试需要在方括号中:

$("a:not([href='#'])")
括号在那里是因为这是你在CSS选择器中进行属性值测试的方式。例如,如果你只是寻找具有href的元素,它看起来像
$("[href='#']")