简体   繁体   English

JavaScript使用数组显示数据

[英]JavaScript using an array to display data

I'm working on a score system that shows per question block, I'm using PHP to retrieve the data from a table and the javascript below to calculate the score. 我正在开发一个显示每个问题块的评分系统,正在使用PHP从表中检索数据,并使用下面的javascript计算分数。 The problem is I want several score labels underneath each question block. 问题是我希望每个问题块下面都有几个分数标签。 So clearly I need an array to make this work, but currently I'm using this line to write the data onto document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1); 显然,我需要一个数组来完成这项工作,但是目前我正在使用此行将数据写入document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1); so this only applies to the first entry in the array. 因此这仅适用于数组中的第一个条目。 How do I make it loop through the entire array(score_label[]) and increase it's value so the code reads document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1); document.getElementById("score_label[1]").innerHTML=""+current_score.toFixed(1); 我如何使其遍历整个数组(score_label [])并增加其值,以便代码读取document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1); document.getElementById("score_label[1]").innerHTML=""+current_score.toFixed(1); document.getElementById("score_label[0]").innerHTML=""+current_score.toFixed(1); document.getElementById("score_label[1]").innerHTML=""+current_score.toFixed(1);

this is the element javascript is writing to 这是javascript正在写入的元素
echo "your total score: <span id='score_label[0]' name='score_board['".$score_board."']'></span>";
if there is need for I can post the entire function but I think it's mostly my lack of knowledge on arrays that's the issue here 如果需要的话,我可以发布整个函数,但是我认为这主要是我对数组缺乏了解

If I'm reading your question correctly ( current_score is the same for all elements???): 如果我正确地阅读了您的问题(所有元素的current_score都相同???):

for (var i = 0; i < score_label.length; ++i)
    document.getElementById("score_label[" + i + "]").innerHTML=""+current_score.toFixed(1);

I should mention that the id attribute of the form score_label[N] may be confusing. 我应该提到, score_label[N]形式的id属性可能令人困惑。

Try to use foreach function to loop through the whole score_label array. 尝试使用foreach函数遍历整个score_label数组。

need to loop through a PHP array in JavaScript 需要遍历JavaScript中的PHP数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM