![](/img/trans.png)
[英]Loop through array, assign each value to an element attribute in Javascript / Jquery
[英]How to assign JS array value to each div in javascript or Jquery?
<script type="text/javascript">
window.onload =init;
function init(){
$rlt = [1, 0, 0];
//How to assign value of $rlt to each div
}
</script>
<div id="block1"></div>
<div id="block5"></div>
<div id="block7"></div>
如何在JavaScript或Jquery中為每個div分配$ rlt的值?
最終結果應為:
<div id="block1">1</div>
<div id="block5">0</div>
<div id="block7">0</div>
干得好:
$( 'div' ).each( function ( i ) {
$( this ).text( $rlt[i] );
});
現場演示: http : //jsfiddle.net/pDwps/1/
或使用常規JavaScript:
[].forEach.call( document.getElementsByTagName( 'div' ), function ( div, i ) {
div.textContent = $rlt[i];
});
現場演示: http : //jsfiddle.net/pDwps/
就像是:
var rlt = [1, 0, 0];
// Only if ID starts with block
$( "[id^=block]" ).each(function( index ){
if( !rtl[index] ) return false; // Stop when out of index.
$( this ).html( rlt[index] );
});
應該這樣做:
$(document).ready(function() {
var $rlt = [1, 0, 0];
$("div[id^=block]").each(function(i) {
$(this).html($rlt[i]);
});
});
假設要向每個div順序添加數組值,可以嘗試此操作,前提是您將jQuery庫包含在頁面中。
$(document).ready(function() {
var $rlt = [1, 0, 0];
$("div[id^=block]").each(function(i) {
$(this).html($rlt[i].toString());
});
});
您可以使用javascript輕松完成此操作。 這個小代碼不需要jQuery。 您可以避免需要jquery插件。
<script type="text/javascript">
window.onload = init;
function init(){
var $rlt = [1, 0, 0];
document.getElementById("block1").innerHTML = $rlt[0];
document.getElementById("block5").innerHTML = $rlt[1];
document.getElementById("block7").innerHTML = $rlt[2];
}
</script>
在這里檢查小提琴: http : //jsfiddle.net/Wk6m8/1/
var divs = getElementsByTagName('div');
for(var i = 0; i < $rlt.length && i < divs.length; i++) {
divs[i].innerHTML = $rlt[i];
}
或為jQuery
替代:
var divs = $('div');
divs.each(function(i, div){
div.innerHTML = $rlt[i];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.