jQuery selector for links with # in href attribute

只愿长相守 提交于 2020-01-10 08:47:10

问题


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)


回答1:


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



回答2:


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


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

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

Check out my jsfiddle!



来源:https://stackoverflow.com/questions/8683116/jquery-selector-for-links-with-in-href-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!