2016-04-03 113 views
2

我正在嘗試使網站顯示90個單獨的div框,然後提示一個年齡段號碼 。然後使用該答案來遮蔽90以內的框的回答量。通過多個div ID進行迭代

如何在最後一個循環中通過div來迭代div?

 for(i = 0; i < 90; i++) { 
     $('body').append('<div id="div'+ i +'" />'); 
     }; 

    var answer = prompt("Whats your age"); 

     for (i = 0; i <= answer; i += 1){ 
     // how can i get this $('#div') below to iterate through the divs? 
     $('#div').css({ "background-color": "red"}); 

     } 

謝謝你們

+1

那麼你的問題是什麼? – HardikDG

回答

3

而不是

$('#div').css({ "background-color": "red"}); 

嘗試

$('#div' + i).css({ "background-color": "red"}); 

DEMO

+0

非常感謝你!!!!! –

+0

@AndrewPiper ...高興地幫助你...;) –

-1

有一個廁所k在.slice()

你的代碼可能看起來像:

for(i = 0; i < 90; i++) { 
    $('body').append('<div class="box" />'); 
}; 

var answer = prompt("Whats your age"); 

$('div.box').slice(0, answer).css({ "background-color": "red"}); 
1

卡爾提克亞Khoslas答案是正確的,但你可以重構你的代碼,只會讓需要儘可能多的div和他們的風格馬上!

var answer = prompt("Whats your age"); 

for (i = 0; i <= answer; i++) { 

    $('<div id="div' + i + '" />') 
     .appendTo('body') 
     .css({ 
      "background-color": "red" 
     }); 

} 

下面是一個例子:https://jsfiddle.net/uc2f2qdq/

0

另一種方法來解決,這是使用jQuery的過濾方法。

$("div[id^='div']").filter(function(index) { 
    return index < answer; 
}).css({ 
    "background-color": "red" 
}); 

在上述代碼段中你得到它有一個id屬性,並與格文本開頭的所有div的。然後你通過索引過濾所有這些結果。只要濾鏡方法內部循環中的當前索引小於回答,元素將獲得紅色背景。

篩選文檔:http://api.jquery.com/filter/

減少匹配元素到那些選擇器或 匹配的傳遞函數的測試。

從性能角度來看,這不是最好的答案,因爲它搜索DOM中具有ID的div元素。爲了獲得更好的性能,您應該縮小搜索範圍,例如在具有特定ID的容器下。

最後但並非最不重要的,這是一個龐然大物。 DEMO

編輯 差點忘了。你應該引入一些條件檢查用戶的答案。例如,如果答案是一個有效的整數,如果它在邊界(0,90)中,或者操作被取消。