问题
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