我有一个非常基本的if else代码,返回“CORRECT”或“INCORRECT”
如何格式化此文本 “正确”出现在GREEN& “INCORRECT”显示为RED
???
<html>
<script language="javascript">
function QA1()
{
var ANSWER = document.getElementById("ANSWER").value;
var RESULT;
if (ANSWER == '2') {
RESULT = "CORRECT";
} else {
RESULT = "INCORRECT";
}
document.getElementById("RESULT1").innerHTML = RESULT;
}
</script>
<body>
<form method="post">
<p><input type="text" length="3" id="ANSWER">
<input type="button" value="Enter" onclick="QA1()"></p>
</form>
<p id="RESULT1"></p>
</body>
</html>
答案 0 :(得分:1)
使用style.color属性修改元素的颜色。
function QA1()
{
var ANSWER = document.getElementById("ANSWER").value;
var resultCorrect = ANSWER === '2' ? true : false;
var result1 = document.getElementById("RESULT1");
var color;
var resultText;
if(resultCorrect)
{
color = 'green';
resultText = 'CORRECT';
}
else
{
color = 'red';
resultText = 'INCORRECT';
}
result1.style.color = color;
result1.innerHTML = resultText;
}
答案 1 :(得分:0)
要更改HTML元素的样式,请使用以下语法:
document.getElementById(id).style.property=new style
以下示例更改
<p>
元素的样式:<html> <body> <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; </script> <p>The paragraph above was changed by a script.</p> </body> </html>
所以你可以这样做:
var element = document.getElementById("RESULT1");
element.innerHTML = RESULT;
element.style.color = RESULT === 'CORRECT' ? 'green' : 'red';