使e.target.value成为一个变量-Javascript



此处为第一个计时器。进入问题。背景:我有一个基于PHQ9问卷的性格测试。目前,我正在从我的PSQL数据库中提取问题,并用Jinja和select/option字段对其进行适当格式化。我可以在开发人员控制台中看到,我正在接收所选选项中的e.target.value

<ol id="questionList">
{% for questions in questions %}
<li class="questions">{{questions.question}}</li>
<select id="options" class="form-select form-select-lg mb-3">
<option selected>Please select an option</option>
<option class="option1" value="0">Not at all</option>
<option class="option2" value="1">Several days</option>
<option class="option3" value="2">More than half the days</option>
<option class="option4" value="3">Nearly every day</option>
</select>
{% endfor %}
</ol>

我使用javascript创建了值的console.log,这样我就可以确保值与指定的级别匹配。例如:一点也不=0,几天=1,等等…

[...document.querySelectorAll("#questionList select")].map((o) =>
o.addEventListener("change", (e) => e.target.value)
);

然而,我很难理解如何破坏console.log并将e.target.value转换为一个变量,该变量可以被推送到分数数组中,并在最后产生一个和。

我想这就是你需要的。最后你还可以看看如何求和数组

let arrayOfScores = [];
[...document.querySelectorAll("#questionList select")].map((o) =>
o.addEventListener("change", (e) => {
arrayOfScores.push(Number(e.target.value))
console.log(arrayOfScores); // This is just to check the array that it works
})
);

或者你可以加一个分数并加上答案值。

let score = 0;
[...document.querySelectorAll("#questionList select")].map((o) =>
o.addEventListener("change", (e) => {
score += Number(e.target.value)
})
);

最新更新