You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AJAX与JSON中显示多HTML实体?星级数量匹配问题求助

解决星级显示问题:根据difficultyLevel生成对应数量的星星

我看到你现在的问题是没法根据JSON里的difficultyLevel值显示对应数量的星级,问题出在你生成星星的代码逻辑上。

问题根源

你当前的代码里用了这行来生成星星:

var starLvl = "⭐" * testObj.difficultyLevel;

在JavaScript中,字符串和数字相乘会返回NaN——JS不会自动把字符串重复对应次数,所以这行代码实际上得到的是无效值,自然没法显示正确的星星数量。

解决方案

你可以用两种方式来生成对应数量的星星:

方法1:使用ES6的repeat()方法(推荐,简洁)

repeat()方法可以直接让字符串重复指定次数,非常适合这个场景:

var starLvl = "⭐".repeat(testObj.difficultyLevel);

方法2:用循环拼接字符串(兼容旧浏览器)

如果需要兼容不支持ES6的旧环境,可以用for循环来拼接星星:

var starLvl = "";
for (var j = 0; j < testObj.difficultyLevel; j++) {
    starLvl += "&#11088;";
}

修改后的完整displayTestResult函数

把原来的星星生成代码替换后,同时补上你遗漏的标签闭合,函数会变成这样:

function displayTestResult(testResultObj){
    // print the testResultObj on the console
    // console.log(testResultObj);
    // construct HTML code to display information
    var html = "<h2>Test Result. Student Reference Number: " + testResultObj.studentRefNumber + "</h2>";
    html += "You scored 6 out of 10";
    html += "<br /><br />";
    html += "<table border='1'>";
    html += "<tr><th>Question</th><th>Content</th><th>Topic</th><th>Correct Answer</th><th>Your Answer</th><th>Difficulty</th></tr>";
    for(var i=0; i < testResultObj.testResult.length; i++){
        var testObj = testResultObj.testResult[i];
        html += "<tr>";
        html += "<td>" + testObj.questionNumber + "</td>";
        html += "<td>" + testObj.content + "</td>";
        html += "<td>" + testObj.topic + "</td>";
        html += "<td>" + testObj.correctAnswer + "</td>";
        if (testObj.yourAnswer == testObj.correctAnswer){
            html += "<td align='center' style='color:green'>";
            html += "&#10003;";
            html += "</td>";
        }else{
            html += "<td align='center'>" + testObj.yourAnswer + "</td>";
        }
        // 替换成正确的星星生成代码
        var starLvl = "&#11088;".repeat(testObj.difficultyLevel);
        html += "<td>" + starLvl + "</td>";
        html += "</tr>"; // 补上遗漏的<tr>闭合标签
    }
    html += "</table>"; // 补上遗漏的表格闭合标签
    var displayDiv = document.getElementById("display");
    displayDiv.innerHTML = html;
}

现在点击按钮后,难度列就会根据difficultyLevel的值显示1到5颗星星了!

内容的提问来源于stack exchange,提问作者bean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 18:12:52