jQuery 如何测试这个 <a> 是否有 href 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11913039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery How to test if this <a> has href attribute
提问by HandiworkNYC.com
Very simple question...
很简单的问题...
for
为了
$('a')
$('a')
How do I test if that jQuery object has an HREF attribute? I'm Looking for something that will return true or false that I can use in an if() statement.
如何测试该 jQuery 对象是否具有 HREF 属性?我正在寻找可以在 if() 语句中使用的返回 true 或 false 的东西。
Thanks!
谢谢!
回答by A Person
jQuery's .attr() function will return undefined if the attribute to be found is missing in the selected element(s).
如果要找到的属性在所选元素中缺失,jQuery 的 .attr() 函数将返回 undefined。
if($('a').attr('href') === undefined) {
// Element 'a' has no href
}
Note: There are other ways to test for undefined
.
注意:还有其他方法可以测试undefined
.
回答by Jarod
if((typeof $('a').attr('href')) !== 'undefined') {
// a has attr href, with 'undefined' not undefined
}
tried with jquery 1.8 on chrome, firefox, safari and ie8.
在 chrome、firefox、safari 和 ie8 上尝试使用 jquery 1.8。
回答by Razan Paul
if(!$('a').attr('href')) {
alert("<a> does not have href attribute");
}
This code also checks for empty links. Note: Jquery attribute values are strings.
此代码还检查空链接。注意:Jquery 属性值是字符串。
回答by adeneo
if ($('a').not($('a:link')).length) {
//you have `<a>` elements that are placeholders only
}