[英]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>
How to assign value of $rlt to each div in javascript or Jquery? 如何在JavaScript或Jquery中为每个div分配$ rlt的值?
Final result should be: 最终结果应为:
<div id="block1">1</div>
<div id="block5">0</div>
<div id="block7">0</div>
Here you go: 干得好:
$( 'div' ).each( function ( i ) {
$( this ).text( $rlt[i] );
});
Live demo: http://jsfiddle.net/pDwps/1/ 现场演示: http : //jsfiddle.net/pDwps/1/
or with regular JavaScript: 或使用常规JavaScript:
[].forEach.call( document.getElementsByTagName( 'div' ), function ( div, i ) {
div.textContent = $rlt[i];
});
Live demo: http://jsfiddle.net/pDwps/ 现场演示: http : //jsfiddle.net/pDwps/
Some thing like: 就像是:
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] );
});
This should do it: 应该这样做:
$(document).ready(function() {
var $rlt = [1, 0, 0];
$("div[id^=block]").each(function(i) {
$(this).html($rlt[i]);
});
});
Assuming you want to add the array values sequentially to each of the divs you can try this provided you include jQuery library into your page. 假设要向每个div顺序添加数组值,可以尝试此操作,前提是您将jQuery库包含在页面中。
$(document).ready(function() {
var $rlt = [1, 0, 0];
$("div[id^=block]").each(function(i) {
$(this).html($rlt[i].toString());
});
});
you can easily do it just using javascript. 您可以使用javascript轻松完成此操作。 jQuery is not required for this small code.
这个小代码不需要jQuery。 you can avoid need of jquery plugin.
您可以避免需要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>
check the fiddle here : http://jsfiddle.net/Wk6m8/1/ 在这里检查小提琴: 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];
}
Or for a jQuery
alternative: 或为
jQuery
替代:
var divs = $('div');
divs.each(function(i, div){
div.innerHTML = $rlt[i];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.