2012-06-21 61 views
7
<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> 

我想循环通过类,但问题是我有card1和card2 id在该页中复制。但上面的代码似乎工作,但显示错误以下。如何检查div是否有id?

Uncaught Type Error: Cannot read property 'length' of undefined 

我想从那里的循环获得ids。

+0

我希望这不会声音粗鲁,但我认为你应该学习莫尔e关于JavaScript,在跳入jQuery之前 – vol7ron

+0

jQuery是一个奇怪的悖论。它的设置使编程JavaScript变得简单,这对初学者来说非常有用;但是,它仍然是JS,所以用户应该首先熟悉至少原生JavaScript对象交互(属性/方法调用) – vol7ron

回答

13

使用属性选择selector[attribute]只得到有一个ID

$('.myClass[id]') // Get .myClass elements that have ID attribute 

你的情况的要素:

$('.ui-droppable[id]').each(function(){ 
    alert(this.id); 
}); 

jsFiddle demo

+2

这也是一个很好的答案,它可以解决问题所在的问题,但不一定要求 – vol7ron

2

如果没有id属性attr方法将返回undefined。只要写:

if($(this).attr("id")) 
-2
var $this = $(this); 
if (typeof $this.attr("id") != "undefined" && $this.attr("id").length > 0) { 
    ... 
} 

如果你打算使用比一次更$(this),它的建议一旦找到它,并把产生的jQuery对象中的局部变量。

12

if(this.id)是你所需要的。


为什么这个工作?

如果元素有一个ID,则该值将是一个非空字符串,其总是计算为true
如果它没有ID,则该值是一个空字符串,其值为false


我试图从循环它们那里得到的ID。

要获得ID列表,你可以使用.map像这样:

var ids = $(".ui-droppable").map(function() {  
    return this.id ? this.id : null; 
}).get(); 

或使用选择Roko suggests in his answer

+0

+1以获得最佳答案 – vol7ron

+0

描述性替代方法:if(this.id && this.id.length > $ somenum)' – vol7ron

1
if(typeof $(this).attr("id") != 'undefined') 
+1

如果'id =“”'怎么办? –