jQuery selector for links with # in href attribute

2019-03-12 01:42发布

I tried to use this jQuery selector:

$("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)

3条回答
The star\"
2楼-- · 2019-03-12 01:57

*= 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 with a #

查看更多
贼婆χ
3楼-- · 2019-03-12 02:15
$("a[href*=#]").click(function(e) {
    e.preventDefault();
    alert('works');
});  
查看更多
smile是对你的礼貌
4楼-- · 2019-03-12 02:20

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

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

Check out my jsfiddle!

查看更多
登录 后发表回答