我有一個div的列表,可能有也可能沒有分配給它們的「highlight」類。從jquery中檢索變量each()
<div id='1' class='box'></div>
<div id='2' class='box highlight'></div>
<div id='3' class='box'></div>
我正在使用jquery each()來標識哪個類具有分配給它的類高亮並獲取該id。
$('.box').each(function(){
if ($(this).hasClass('highlight')){
var id = $(this).attr('id');//get the id
console.log('It has the class = ' + id);//this shows correctly
}
});
//outside of the each()
console.log('id = ' + id);//this does not show the id "undefined"
當我嘗試檢索each()之外的id時,它是未定義的。有什麼方法可以檢索它嗎?
這是由於範圍界定?變量id在if語句中定義。 – CoolBeans 2011-03-19 18:51:11