jQuery selector for links with # in href attribute

前端 未结 3 1669
耶瑟儿~
耶瑟儿~ 2020-12-29 03:44

I tried to use this jQuery selector:

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

but it doesn\'t seem to work. I

相关标签:
3条回答
  • 2020-12-29 03:53

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

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

    Check out my jsfiddle!

    0 讨论(0)
  • 2020-12-29 04:00
    $("a[href*=#]").click(function(e) {
        e.preventDefault();
        alert('works');
    });  
    
    0 讨论(0)
  • 2020-12-29 04:06

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

    0 讨论(0)
提交回复
热议问题