2011-03-19 59 views
0

我有一個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時,它是未定義的。有什麼方法可以檢索它嗎?

+0

這是由於範圍界定?變量id在if語句中定義。 – CoolBeans 2011-03-19 18:51:11

回答

3

最簡單的方法是做它沒有一個循環:

var id = $('.box.highlight').attr('id'); 

但是,使其與工作循環,你需要在循環之前聲明id變量:

var id; 

$('.box').each(function(){ 
    if ($(this).hasClass('highlight')){ 
     id = $(this).attr('id');//get the id  
    }      
}); 

問題是variable scope,你應該閱讀有關。

+0

感謝您的額外信息。 – Jason 2011-03-19 18:58:56

0

你可以做,而不是$('.box.highlight').attr('id');

如果你真的想訪問用於您需要定義一個函數外部變量.each()內部功能的變量之外。請注意,這不會對異步調用的工作以同樣的方式,但應與.each()

var id; 
$('.box').each(function(){ 
    if ($(this).hasClass('highlight')){ 
     id = $(this).attr('id');//get the id  
     console.log('It has the class = ' + id);//this shows correctly 
    }      
}); 
console.log('id', id); 
0

更新在適當的範圍的變量:

var id; 
$('.box').each(function(){ 
     if ($(this).hasClass('highlight')){ 
      id = $(this).attr('id');//get the id  
      console.log('It has the class = ' + id);//this shows correctly 
     }      
    }); 
0

var關鍵字使得可變id本地的功能。嘗試只是說id = ...

+1

在您打算使用'id'的範圍中使用'var id'總是一個好主意;否則你有效地聲明一個全局變量。 – meagar 2011-03-19 18:49:57

0

javascript中的變量作用域是通過函數實現的,所以當你在.each(function() { var id; })中聲明該變量時,它只能在那裏訪問。如果您希望在該功能之外訪問它,則應該在.each之前聲明它,但仍可以在.each內使用它。由於它的範圍更加全球化,因此變量名稱應該更具體,然後只是id,也許使用boxHighlightId