jQuery 带有# in href 属性的链接的jQuery选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8683116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:53:19  来源:igfitidea点击:

jQuery selector for links with # in href attribute

jqueryjquery-selectors

提问by simPod

I tried to use this jQuery selector:

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

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

but it doesn't seem to work. I would like to select all tags which have anchor in href attribute (has # symbol there)

但它似乎不起作用。我想选择所有在 href 属性中有锚点的标签(那里有 # 符号)

回答by epignosisx

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

回答by Adam Rackis

*=will filter attributes that contain the given string anywhere

*=将过滤在任何地方包含给定字符串的属性

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

Also note that

还要注意的是

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

will select any anchor whose href starts witha #

将选择其 hrefa开头的任何锚点#

回答by Korvin Szanto

You've got to select using the attribute starts with selector:

您必须使用以 selector 开头属性进行选择

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

Check out my jsfiddle!

看看我的 jsfiddle