2016-10-17 36 views
0

我想這個功能打印球圖片的數量或消防車的圖片在用戶點擊數:試圖爲特定圖像類型追加圖像計數| jQuery的

function imageCounter(){ 

var ballCount = 0; 
var truckCount = 0; 

$('img[src*=ball]').each(function(){ 
    if($(this).prop("checked")){ 
     ballCount+=1; 
    }  
    $('#radioButtons').append("There are " + ballCount + " ball images."); 
}); 


$('img[src*=truck]').each(function(){ 
    if($(this).prop("checked")){ 
     truckCount+=1; 
    } 
    $('#radioButtons').append("There are " + truckCount + " truck images."); 
    }); 

} 

我覺得我接近..

我有4個球圖像,和1輛救火車圖像。我的代碼目前不給我圖像的數字值,而是打印輸出消息4次的球,1次的消防員。

有關從哪裏出發的建議?

回答

1

你只需要追加消息行搬出foreach循環的:

function imageCounter() { 

    var ballCount = 0; 
    var truckCount = 0; 

    $('img[src*=ball]').each(function() { 
    if ($(this).prop("checked")) { 
     ballCount += 1; 
    } 
    }); 

    $('#radioButtons').append("There are " + ballCount + " ball images."); 

    $('img[src*=truck]').each(function() { 
    if ($(this).prop("checked")) { 
     truckCount += 1; 
    } 
    }); 
    $('#radioButtons').append("There are " + truckCount + " truck images."); 
} 
+0

這是非常多的。您也可以在底部打印出一條消息,或者在兩個循環之後再次使用變量做其他事情。 – Blizzardengle

+0

這是有效的,現在它不是根據圖像的數量重複每個句子。但它也只是給我0的圖像數量,它根本不考慮我的計數器:/有什麼想法爲什麼? – MrJesus

1

我注意到有兩件事情。首先,$(this).prop("checked")將在<img>標記上調用,除非您將它們設置爲在其他地方未在此處顯示的代碼中進行檢查,否則它們不會被檢查。 (意爲truckCountballCount不增加)

第二個是事實$('#radioButtons').append(...)是被稱爲你的每一個「循環」中這麼說,因此將追加該行對每個<img>標記,選擇相匹配。

+0

+1也值得注意,'checked'不是'img'標籤的屬性,因此如果你添加了通過標記檢查,那麼你需要使用'.attr'來檢索它,除非你使用' .prop'在JS – MugiwaraUK

+0

謝謝!讓我回去研究'檢查'實際上在做什麼。決定完全採取行動。並且如果($(this).attr('src')) – MrJesus