2012-07-14 53 views

回答

1

試試這個

Live Demo

//This will give you ids of all the controls have the specified class 
$('.className').each(function(){ 
    alert(this.id); 
}); 
+0

感謝阿迪爾......我只是覺得打開我的眼睛的jQuery simpliciy的世界...... – manoj 2012-07-14 07:07:17

+0

你,歡迎@manoj – Adil 2012-07-14 07:08:08

0

你可以同時使用它們像$('#id.class')

0
function getIDs(className) 
{ 
    var ids = []; 

    $('.' + className).each(function() 
    { 
     var id = $(this).attr('id'); 
     if (id) ids.push(id); 
    }); 
    return ids; 
} 
3

使用指定的類循環所有元素,並將它們的ID存儲在數組中。見jQuery .each

var ids = []; 
$('.class').each(function() { 
    if($(this).attr('id')) 
     ids.push($(this).attr('id')); 
}); 
+0

感謝,,就像魔術.. – manoj 2012-07-14 06:57:12

+0

@ manoj沒問題,很樂意幫忙:) – nbrooks 2012-07-14 06:58:55

0
function getAllIds(className){ 
     var results = []; 
     $(className).each(function(){ 
       results.push($(this).attr('id')); 

     }); 
     return results; 
    } 
1

使用jQuery:

var ids = $(".class").map(function() { 
    return this.id.length > 0 ? this.id : null; 
}).get(); 

檢查,如果id.length> 0確保你沒有從元素空字符串沒有ID。

DEMO:http://jsfiddle.net/T8YuD/

+0

@VisioN調用結束時.get()的目的是什麼?它不會改變我能說的任何事情。你能解釋一下嗎? – Ehryk 2012-07-14 11:05:38

+0

'get()'返回一個基本的JavaScript數組,而不是jQuery-wrapped數組。閱讀[文檔](http://api.jquery.com/map/)中的更多信息。你也可以在DEMO中看到不同之處。 – VisioN 2012-07-14 14:23:05

相關問題