jQuery: Easy way to check if a href attribute is valid

笑着哭i 提交于 2021-02-10 04:22:32

问题


I am looking for a pretty easy way to check when somebody clicks a link that it's valid.

Good

 <a href="index.html">some link</a>

Bad:

<a href="#">some link</a>
<a href="javascript:void(0);">some link</a>

回答1:


Just check for the href value:

$('a').click(function(){
  var bad = this.href.lastIndexOf('#') >= 0 || this.href.indexOf('javascript') >= 0;
  alert(bad ? 'Bad' : 'Good');
  return false;
});

Demo




回答2:


There is no really "easy" way, you have to get the value of the href and do an ajax call to it like so :

var url = $('a').attr('href');
    $.ajax({
        url:url,
        type:'HEAD',
        error: function()
        {
            //file not exists
        },
        success: function()
        {
            //file exists
        }
    });


来源:https://stackoverflow.com/questions/9212882/jquery-easy-way-to-check-if-a-href-attribute-is-valid

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