Javascript 检查 jQuery 中是否存在 Attribute('id')
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12625717/
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
Check if Attribute('id') Exists in jQuery
提问by CodeMan5000
How can I check if an attribute Id exists in jQuery?
如何检查 jQuery 中是否存在属性 Id?
I searched around and found that this should work:
我四处搜索,发现这应该有效:
if ($(this).attr('id').attr('id'))
{
}
I still get this error: TypeError: Object gauge1 has no method 'attr'
我仍然收到此错误:TypeError: Object Gauge1 has no method 'attr'
回答by Adriano Carneiro
This itself will work:
这本身会起作用:
if($(this).attr("id"))
Check existing jsfiddle on the issue: http://jsfiddle.net/rwaldron/wVqvr/4/
检查现有的 jsfiddle 问题:http: //jsfiddle.net/rwaldron/wVqvr/4/
回答by Selvakumar Arumugam
Just try it the old way
用旧方法试试
if (this.id) {
//do something
}
回答by Guffa
You can use the is
methodand the Has Attribute Selector:
您可以使用该is
方法和Has Attribute Selector:
if ($(this).is('[id]')) {
}
回答by tarun
if ($(this).attr('id')){
alert(id);
}
if ($(this).attr('id')){
alert(id);
}
回答by Gromer
HTML:
HTML:
<div class="hey"></div>
<div class="you" id="woah"></div>
<div id="results"></div>?
jQuery:
jQuery:
var id = $('div.hey').attr('id');
if (id) {
// Have an id.
} else {
// Don't have an id.
}
A fiddle: http://jsfiddle.net/NEVYT/
回答by Travis J
you could also just use the plain js object
你也可以只使用普通的 js 对象
if( this.id !== undefined && this.id.length > 0 ){
//todo: use id
}