简体   繁体   English

Javascript如何比较两个值,然后更改背景颜色?

[英]Javascript How do i compare two values and then change background color?

Why doesn't this code work? 为什么此代码不起作用? I want it to change the color of the input background whether the value is correct (green) or not (red). 我希望它更改输入背景的颜色,无论该值正确(绿色)还是错误(红色)。

<html>
<head>
<script type="text/javascript">
function funct1 () {
var username = "63XZ4";
if(username == document.getElementById('keygen').value ) {

document.getElementById('keygen').style.backgroundColor = '#5bc556';
}

else {
colorchange.style.backgroundColor = 'red';
}
}
return 0;
</script>
</head>
<body>
<input type="text" id="keygen">
<button onclick="funct1"></button>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function funct1 () {
    var username = "63XZ4";
    var keygen = document.getElementById('keygen');
    if(username == keygen.value) {
        keygen.style.backgroundColor = '#5bc556';
    } else {
        keygen.style.backgroundColor = 'red';
    }
}
</script>
</head>
<body>
<input type="text" id="keygen" />
<button onclick="funct1()">Button Title</button>
</body>
</html>

The above should help. 以上应该会有所帮助。 Also, you may want to look into this: 另外,您可能需要研究以下内容:

  • Give more descriptive names to functions you declare. 为您声明的函数指定更多描述性名称。
  • Save time by eliminating calls to "getElementById" by storing DOM elements in variables. 通过将DOM元素存储在变量中来消除对“ getElementById”的调用,从而节省时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM