javascript document.getElementById循环

时间:2017-04-12 23:12:56

标签: javascript

我正在努力使这个打印出我创建的数组中的等级。我可以让我的 for 循环循环遍历数组中的所有等级,但它只打印出最后一个等级。我设置为每次 for 循环完成一个循环时打印等级,但正如我所说,它只打印出最后一个等级。我也尝试使用.innerHTML,但这不会像你在代码中看到的那样起作用:

var arrayTest = [78, 65, 41, 99, 100, 81];
var arrayLength = arrayTest.length;
var midtermTest = 60;
var msg = "";
var grade;

arrayOfGrades();
addBonus();

function tellGrade() {
    if (grade > 100) {
        msg = "Grade is higher than 100!, " + grade;
    }
    else if (grade >= 90) {
        msg = "You got an A " + grade + "!!, ";
    }
    else if (grade >= 80) {
        msg = "You got a B " + grade + "!!, ";
    }
    else if (grade >= 70) {
        msg = "You got a C " + grade + "!!, ";
    }
    else if (grade >= 60) {
        msg = "You got a D " + grade + "!!, ";
    }
    else if (grade <= 59) {
        msg = "You got a F " + grade + "!! :(, ";
    }
    else if (grade < 0) {
        msg = "Grade is less than 0, " + grade;
    }
}

function arrayOfGrades() {
    for (var i = 0; i < arrayLength; i++) {
        grade = arrayTest[i];
        tellGrade(grade);
        writeGrade();
    }
}
function addBonus()
{
    midtermTest = midtermTest + (midtermTest * .05);
    grade = midtermTest;
    tellGrade(grade);
    writeMidtermGrade();
}

function writeGrade() {
    //document.getElementById("test").innerHTML = "Test grade letter: " + msg.toString() + "<br />";
    var el = document.getElementById('test');
    el.textContent = "Test grade letter: " + msg.toString();
}


function writeMidtermGrade() {
    var el = document.getElementById('midterm');
    el.textContent = "Midterm test grade letter: " + msg.toString();
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>DecisionsAndLoopsAssignment1_Byrd</title>
    <link href="css/default.css" rel="stylesheet" />
</head>
<body>
    <div id="test">Missing grade!!</div>
    <div id="midterm">Missing grade!!</div>
    <script src="js/main.js"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

函数writeGrade()会覆盖它输出到的元素中可能已经存在的内容。因此,当多次调用时,只保留最后一个值。使用.innerHTML会做同样的事情。将内容字符串累积到单个var然后进行单个调用以输出它们是解决此问题的一个选项。

我还注意到你在全球变量中传递临时值,这通常被视为不良形式。

答案 1 :(得分:0)

您正在设置元素的整体内容,而不仅仅是添加元素。这将不断覆盖上一次循环迭代的工作,因此您只会看到最后的结果,导致计算机速度很快。

您有两个选项,阅读元素的textContent,然后继续添加它。这个概念称为自我分配。

var aMessage = "Hello, ";
aMessage += "World!";
console.log(aMessage") // => "Hello, World!"

虽然一般我们会创建一个新元素并将该元素作为子元素附加

&#13;
&#13;
var msg = "A+"; // this should be a variable to our function vs a global va

function writeGrade() {
    var el = document.getElementById('test');
    var newEl = document.createElement("p");
    newEl.textContent = "Test grade letter: " + msg.toString();
    el.appendChild(newEl)
}

writeGrade()
&#13;
<div id="test"> 

</div>
&#13;
&#13;
&#13;