Javascript 如何检查div是否有id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11137317/
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
how to check if div has id or not?
提问by jit
<div id="cardSlots">
<div class="ui-droppable" tabindex="-1" id="card1">one</div>
<div class="ui-droppable" tabindex="-1" id="card2">two</div>
<div class="ui-droppable" tabindex="-1">three</div>
<div class="ui-droppable" tabindex="-1">four</div>
</div>
<script>
$(".ui-droppable").each(function () {
if($(this).attr("id").length>0)
{
alert('here');
}
});
</script>
I am trying to loop through class but issue is i have card1 and card2 ids duplicate in that page. but above code seems to work but showing below error.
我正在尝试遍历类,但问题是我在该页面中有 card1 和 card2 id 重复。但上面的代码似乎有效但显示以下错误。
Uncaught Type Error: Cannot read property 'length' of undefined
I am trying to get ids from the loop which are there.
我试图从那里的循环中获取 id。
回答by Roko C. Buljan
Use attribute selectorselector[attribute]
to get only the elements that have an ID
使用属性选择器selector[attribute]
仅获取具有 ID 的元素
$('.myClass[id]') // Get .myClass elements that have ID attribute
In your case:
在你的情况下:
$('.ui-droppable[id]').each(function(){
alert( this.id );
});
回答by Felix Kling
if(this.id)
is all you need.
if(this.id)
是你所需要的全部。
Why will this work?
为什么这会起作用?
If the element has an ID, the value will a non-empty string, which always evaluates to true
.
If it does not have an ID, the value is an empty string which evaluates to false
.
如果元素具有 ID,则该值将是一个非空字符串,其计算结果始终为true
。
如果它没有 ID,则值为一个空字符串,其计算结果为false
。
I am trying to get ids from the loop which are there.
我试图从那里的循环中获取 id。
To get a list of IDs, you can use .map
like so:
要获取 ID 列表,您可以.map
像这样使用:
var ids = $(".ui-droppable").map(function() {
return this.id ? this.id : null;
}).get();
or use the selector Roko suggests in his answer.
或使用Roko 在他的回答中建议的选择器。
回答by Tats_innit
demohttp://jsfiddle.net/QRv6d/13/
演示http://jsfiddle.net/QRv6d/13/
APi link: http://api.jquery.com/prop/
API链接:http: //api.jquery.com/prop/
Please try this, this should help
请试试这个,这应该会有所帮助
code
代码
$(".ui-droppable").each(function () {
if($(this).prop("id").length > 0)
{
alert('here');
}
});?
回答by antyrat
If there is no id
attribute attr
method will return undefined
. Just write:
如果没有id
属性attr
方法将返回undefined
。写就好了:
if($(this).attr("id"))
回答by Talha
if(typeof $(this).attr("id") != 'undefined')
回答by Cyrille
var $this = $(this);
if (typeof $this.attr("id") != "undefined" && $this.attr("id").length > 0) {
...
}
If you're going to use $(this)
more than once, it's advised to find it once, and put the resulting jQuery object in a local variable.
如果要$(this)
多次使用,建议查找一次,并将生成的 jQuery 对象放在局部变量中。