很简单的问题...jQuery的如何测试,如果这<a>有href属性
为
$('a')
如何测试如果jQuery对象具有HREF属性?我正在寻找能够返回真或假的东西,我可以在if()语句中使用它。
谢谢!
很简单的问题...jQuery的如何测试,如果这<a>有href属性
为
$('a')
如何测试如果jQuery对象具有HREF属性?我正在寻找能够返回真或假的东西,我可以在if()语句中使用它。
谢谢!
如果在所选元素中缺少要查找的属性,jQuery的.attr()函数将返回undefined。
if($('a').attr('href') === undefined) {
// Element 'a' has no href
}
注意:还有其他方法可以测试undefined
。
这是更好的吗? if(typeof $ this.attr('href')===“undefined”) – 2012-08-11 08:41:40
有很多方法可以做到这一点,但它也可以。编辑:等待,它的'如果(typeof $(this).attr('href')===“undefined”)' – 2012-08-11 08:42:49
if ($('a').not($('a:link')).length) {
//you have `<a>` elements that are placeholders only
}
if((typeof $('a').attr('href')) !== 'undefined') {
// a has attr href, with 'undefined' not undefined
}
在Chrome,Firefox,Safari和IE8试图用jQuery 1.8。
if(!$('a').attr('href')) {
alert("<a> does not have href attribute");
}
此代码还检查空链接。注意:Jquery属性值是字符串。
是否要检查与空HREF元素属性为好,或者仅仅是一个拥有所有没有指定href属性,这当然是无效的HTML元素。 – adeneo 2012-08-11 08:05:21
我想检查具有* no * href属性的元素。在HTML5 href不是必需的 – 2012-08-11 08:11:08
是的,但这将使它成为一个占位符,并且它们可以以不同的方式定位,请参见[FIDDLE](http://jsfiddle.net/J6rCF/)... – adeneo 2012-08-11 08:23:16