javascript - 在 .js var 中应用 CSS 样式

标签 javascript html css

我目前正在构建一个游戏,该游戏依赖随机数来显示 .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

  }

密码本

https://codepen.io/damPop/pen/ZwvvGV?editors=0010

关于javascript - 在 .js var 中应用 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54583760/

相关文章:

javascript - HTML canvas 到 IE9、10 中的可下载文件

javascript - 使用 jQuery 将输入值从一页传递到新页面上的输入值

php - 如何在 html textarea POST 数据中保留换行符

javascript - Angular2 参数化路由器链接组件不完全刷新

javascript - 利用 JavaScript 的 eval() 方法

javascript - _createElement 方法的目的是什么?

html - 使用 CSS3 从右到左排列/重复 Div

javascript - 如何使用 if 语句删除和添加类?

html - ngx 数据表垂直滚动,行高设置为自动

html - 使用 :before 添加与 float 列相同高度的行