2012-02-10 77 views
1

嘿我想通过一个类进行搜索并检查该类是否包含某个id。我必须使用.each吗?如果我这样做,我不知道如何准确使用它,可能会有人告诉我如何使用它在这方面, 任何帮助表示赞赏jquery搜索througha类检查它是否有一个特定的ID

if(id == $('.people').attr('id')) 
    { 
     alert("person exists"); 
    } 

回答

3

因为IDS不应该使用超过一次,你根本就做:

if($('#' + id + '.people').length >= 1) 
    alert('person exists'); 
3

您可以搜索ID与

$('#my-id') 

在你的情况,

$('#' + id) 

您可以检查,如果结果是测试为空length

if($('#'+id).length == 0) 

为了验证它是否具有给定ID的.person元素,你可以测试

if($('.person#'+id).length > 0) { 
    alert('person exists'); 
} 
+0

哎呀,你是对的!谢谢! – 2012-02-10 23:31:58

0

由于id只能用于一次,而不是搜索具有该id的元素并检查它是否具有该类。这将是更快:

$('#the-id').hasClass('the-class'); 
0

一个解决方案是使用一个简单的选择,并检查该元素存在。

if ($('.people#'+id).length()) { //Checking length() checks if element exists 
    alert("person exists"); 
} 
相关问题