最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Easy way to check if a href attribute is valid - Stack Overflow

programmeradmin2浏览0评论

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>

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>
Share asked Feb 9, 2012 at 14:42 user759235user759235 2,2073 gold badges42 silver badges85 bronze badges 2
  • use regex for your specific format – xkeshav Commented Feb 9, 2012 at 14:45
  • Yes but all that i found where patterns that check a plete url, included the 'www.', this is not going to work for urls like index.html :-) (didn't found any patterns for this yes) – user759235 Commented Feb 9, 2012 at 15:12
Add a ment  | 

2 Answers 2

Reset to default 4

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

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
        }
    });
发布评论

评论列表(0)

  1. 暂无评论