需要脚本通过输入更改div背景..不工作

时间:2012-04-09 04:41:06

标签: html input background-color

我想更改包含输入字段的DIV的背景颜色。当您在输入中键入数据时,我将代码正常工作,背景颜色变为红色。但当我返回并删除数据时,输入字段为空白,背景不会恢复为原始颜色。

我需要DIV的背景颜色在空白时恢复原来的颜色。

我做错了什么?

这是我的代码:

<script>
$(document).ready(function(){

$("#id").keypress(function() {
if($("#id").val().length > 0) $("#in").css("background-color", "red");
 else {
   if($("#id").val().length = 0) $("#in").css("background-color", "grey"); 
 }

 });
 });
 </script>

3 个答案:

答案 0 :(得分:0)

你有一个错误:

else {
if($("#id").val().length = 0)

应该是:

else {
if($("#id").val().length == 0)

另外,永远不要忽略Javascript中的if语句。

答案 1 :(得分:0)


$(document).ready(function(){

$("#id").keypress(function() {
if($("#id").val().length > 0) $("#in").css("background-color", "red");
 else {
  if($("#id").val().length == 0) $("#in").css("background-color", "grey");
 }

 });
 });

答案 2 :(得分:0)

除了已经提到过的bug之外,试试这个。 把这两个类放在你的css文件中:

.greyColor
{
background-color: grey;
}

.redColor
{
background-color: red;
}

在你的javascript中使用addClass和removeClass函数:

<script>
$(document).ready(function(){
$("#id").keypress(function() {
if($("#id").val().length > 0)
{
    $("#in").addClass("redColor");
}
else {
   if($("#id").val().length == 0) 
{
$("#in").addClass("greyColor");
$("#in").removeClass("redColor");
}
}

});
});
</script>