如何检查div是否有id?

jit*_*jit 7 javascript jquery

<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>
Run Code Online (Sandbox Code Playgroud)

我试图循环通过类,但问题是我有card1和card2 ID在该页面重复.但上面的代码似乎工作,但显示下面的错误.

Uncaught Type Error: Cannot read property 'length' of undefined
Run Code Online (Sandbox Code Playgroud)

我试图从循环中获取ID.

Rok*_*jan 13

使用属性选择器 selector[attribute]仅获取具有ID的元素

$('.myClass[id]')   // Get .myClass elements that have ID attribute
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

$('.ui-droppable[id]').each(function(){
   alert( this.id );
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle演示

  • 这也是一个很好的答案,可以解决问题所在,但不一定要问 (2认同)

Fel*_*ing 12

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


为什么会这样?

如果元素具有ID,则该值将为非空字符串,该字符串始终求值为true.
如果它没有ID,则该值为空字符串,其值为false.


我试图从循环中获取ID.

要获取ID列表,您可以这样使用.map:

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

或者使用Roko在他的回答中建议的选择器.