2010-12-09 62 views
0

我在這裏要做的是通過jQuery的.each()圖像列表循環,並測試我傳遞給該函數的src是否已經存在名單。如果它不是我想要添加它,如果我不想做任何事情。我在哪裏把代碼添加新的圖像記霸菱我只希望每一個()迭代後要做到這一點是在內部測試.each()和突破

這裏是我到目前爲止

function addFriendImage(imageSrc){ //Adds the image of the friend to the sidebar 

    var imgReturn = $('ul.friendImages li img').each(function(){ 
     var currentImageSrc = $(this).attr('src'); 
     if(currentImageSrc == imageSrc){ 
      return false; 
     } 
    }); 

    if(imgReturn != false){//does this make sense? 
     //I'll add an new image, (I can work out to do this bit myself) 
    } 
} 

我是新來的javascript和jquery,所以我可能出錯了語法。 任何反饋將不勝感激。

回答

1

您可以跳過循環,只是找到屬性你正在尋找的SRC所有圖像,使用jQuery [attribute="value"]選擇:

function addFriendImage(imageSrc){ //Adds the image of the friend to the sidebar 

    if ($('ul.friendImages li img[src="' + imageSrc + '"]').length) { 
     // img with src attribute matching imageSrc exists 
    } else { 
     // img doesn't exist 
    } 

} 

不能從$.each返回值,因爲它總是返回用於調用鏈接的jQuery對象。但是,返回true/false的確有其特殊含義:返回false的行爲類似於break;語句,並且停止迭代,而返回true的行爲類似於continue語句,可以及早停止當前迭代並繼續執行下一個迭代。

+0

非常感謝解決方案,但最重要的是解釋。我傾向於過分複雜我的代碼。我想這是學習過程的一部分。 – willmcneilly 2010-12-09 01:48:51

+0

沒問題。學習用jQuery來補充你的JavaScript並不難。學習正確使用jQuery *需要時間。 – meagar 2010-12-09 01:52:15

1

你可以避免所有額外的東西,並直接查詢它。

if(!($('ul.friendImages li img[src=' + imageSrc + ']').length)){ 
}