jQuery选择器:选取href属性中包含“#”的链接

31

我尝试使用这个jQuery选择器:

$("a:has(href*=#)").click(function() {
     alert('works');
});  

但似乎它不起作用。我想选择所有href属性中带有锚点(即#符号)的<a>标签。

3个回答

70
$("a[href*=#]").click(function(e) {
    e.preventDefault();
    alert('works');
});  

我相信@simPod试图选择<a href='#'>的情况,而不是<a href='link.com/page/#hash'>的情况。 - Korvin Szanto
2
从 @simPod 的澄清来看,我们都错了!他想要的是 http://api.jquery.com/attribute-starts-with-selector/。 - Korvin Szanto
需要在选择器中使用单引号 - $("a[href*='#']") - Rauli Rajande
嗨 @epignosisx。我觉得最新的jQuery中选择器 a[href*=#] 不起作用。 - maheshwaghmare
9
在某些情况下它不起作用。如果你想要更可靠的结果,你应该像这样转义#$('a[href*=\\#]') - lurkit
显示剩余2条评论

51

*=将筛选包含给定字符串的属性,不管其位置在哪里

$("a[href*='#']").click(function() {
    alert('works');
});

同时请注意

$("a[href^='#']").click(function() {
    alert('works');
});

将选择任何 href 属性以 # 开头的锚点。


你是唯一一个添加了以属性开头选择器的人,这恰好是他真正想要的=D gj - Korvin Szanto
我原以为我的问题很清晰,但它比看起来更复杂 :D - simPod
呵呵 - 很多时候,jQuery的解决方案比你想象的要简单 :) - Adam Rackis
谢谢^=选择器,这就是我一直在寻找的! - calvinf

19

attribute-contains选择器,因为href属性不等于#。此外,API明确指出,被评估的值必须用引号括起来。 - David Thomas
@DavidThomas,他正在尝试选择<a href='#'>的情况,而不是像<a href='index.php#header'>这样的情况。另外,感谢您指出引用=D的问题。 - Korvin Szanto
实际上,我需要选择#header,而我想到的方法是选择所有在href中带有#<a> - simPod
1
在这种情况下,您需要使用$('a[href=^"#"]')来防止选择像http://en.wikipedia.org/wiki/Random#A_number_is_.22due.22这样的href。我已更新我的答案! - Korvin Szanto
@KorvinSzanto,你的小提琴正在工作,但这里的代码有一个小错误,^符号应该在等号之前。 - chodorowicz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接