我目前正在构建一个游戏,该游戏依赖随机数来显示 .js 文件中数组中的特定字符串。我想要做的是有效地将 span 元素应用于数组中的某些文本 - 例如。使积极的结果变成绿色和消极的红色,但是我不知道如何在 html 之外做到这一点。例如:
var data = [
{"label": "Question 1", "value": 1, "question": "Awareness: High, Consistency: Low."},
{"label": "Question 2", "value": 1, "question": "Consistency: High, Awareness: Low."},
]
单独的一组代码,选择一个随机数后,返回data[i].label。我如何在 js 中设置跨度,以便“高”字符串返回绿色,“低”字符串返回红色?
干杯。
最佳答案
你没有具体说明,但我去做了我能做的。
首先,你的跨度
<span id="result">here we go</span>
CSS 文件,极简主义,我没有为此包含 Bootstrap。
span {color:green}
.red{color:red}
JS,没有事件,或者事件处理程序。
var data = [
{"label": "问题 1", "value": 1, "question": "意识:高,一致性:低。"}, {"label": "问题 2", "value": 1, "question": "一致性:高,意识:低。"} ]
数组,我已经删除了第二个对象之后的尾随逗号。
let outputs = data[0].question; This will hold the result from the array, data[0] targets the first object, you can also get map over the properties, but you have not entirely specified the scope and desired functionality.
var output = document.getElementById('result'); // the span element
output.innerText = outputs; // i prefer innerText to innerHTML
if (outputs.includes("Consistency: Low")) { // new string method includes, you can pass the whole ("Consistency: Low")in with no worries.
output.classList.toggle("red"); // if condidtion is true, toggle the red class
}
密码本
关于javascript - 在 .js var 中应用 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54583760/