2012-02-10 37 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"); 
} 
相關問題