在.js var中应用CSS样式

时间:2019-02-07 23:12:01

标签: 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中设置跨度,以使“高”字符串返回绿色,而“低”字符串返回红色?

干杯。

2 个答案:

答案 0 :(得分:0)

您没有指定太多,但是我去尽了我所能。

首先,您的跨度

<span id="result">here we go</span>

CSS文件,最低限度,我没有为此提供Bootstrap。

span {color:green}
.red{color:red}

JS,no事件或事件处理程序。

var data = [

{“标签”:“问题1”,“值”:1,“问题”:“意识:高,一致性:低。”}, {“标签”:“问题2”,“值”:1,“问题”:“一致性:高,知名度:低。”} ]

数组,我删除了第二个对象之后的结尾逗号。

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

  }

Codepen

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

答案 1 :(得分:-1)

使用类

var data = [
  {label: "Question 1", value: 1, awareness: 'High', consistency: 'Low' },
  {label: "Question 2", value: 1, awareness: 'Low', consistency: 'High' },
  {label: "Question 3", value: 1, awareness: 'Low', consistency: 'Low' },
  {label: "Question 4", value: 1, awareness: 'High', consistency: 'High' }
];

const questionElement = document.getElementById('question');
const awarenessElement = document.getElementById('awareness');
const consistencyElement = document.getElementById('consistency');

document.getElementById('select').addEventListener('click', select);

select();

function select() {
  const question = data[Math.floor(Math.random() * 4)];
  questionElement.innerText = question.label;
  awarenessElement.innerText = `Awareness: ${question.awareness}`;
  awarenessElement.className = question.awareness;
  consistencyElement.innerText = `Consistency: ${question.consistency}`;
  consistencyElement.className = question.consistency;
}
.High {
  background-color: green;
}

.Low {
  background-color: red;
}
<span id="question"></span>
<div id="awareness"></div>
<div id="consistency"></div>

<button id="select">Select</button>