jquery find id属性是否存在

时间:2013-07-30 09:03:47

标签: jquery

我试图找到engage_app的所有元素,这些元素都有id,哪些没有id。以下代码有什么问题?它找不到有/无ids的那些

jQuery('.engagement_data').each(function() {

   var engagement_app = $(this).find(".engagement_app").val();
   //if ($(this).find(".engagement_app").attr('id'))
   if ($(this).find(".engagement_app").is('[id]'))
   {
      console.log("in if1")
      console.log($(this).find(".engagement_app").attr('id'));
   }

   if ($(this).find(".engagement_app").not('[id]'))
   {
        console.log("id not found")
   }
});

4 个答案:

答案 0 :(得分:2)

试试这个 -

使用!代替not

if (! $(this).find(".engagement_app").is('[id]')){
    console.log("id not found")
}else{
    console.log("in if1")
    console.log($(this).find(".engagement_app").attr('id'));
}

答案 1 :(得分:0)

如果你想要有{id 1}的"all the elements of engagement_app"(孩子?),你应该使用这样的东西。

var els_with_id = $(this).find(".engagement_app *[id]") 

var els_without_ids = $(this).find(".engagement_app *").not("[id]")

答案 2 :(得分:0)

您可以使用

$('.engagement_app [id]')

查找具有ID和

的所有元素
$('.engagement_app :not([id])')

查找没有ID的所有元素。

这是一个演示如何运作的小提琴:

http://jsfiddle.net/qj3V7/

答案 3 :(得分:0)

<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){

$(".engagement_app").each(function(){
var id = $(this).attr("id");

if(id==undefined)
{
  console.log("id not found")
}
else
{
  console.log("in if1");
  console.log($(this).attr('id'));
}
});


});
</script>
</head>
<body>
<div class="engagement_data">
<div class="engagement_app" id="1">1</div>
    <div class="engagement_app">2</div>
    <div class="engagement_app" id="3">3</div>
    <div class="engagement_app">4</div>
</div>

</body>
</html>
相关问题