2012-04-09 76 views
0

我想更改包含我的输入字段的DIV的背景颜色。当您在输入中输入数据时,代码正常工作,背景颜色变为红色。但是,当我返回并清除输入字段留空的数据时,背景不会回到原来的颜色。需要脚本通过输入更改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> 

回答

0

你有一个错误:

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

应该是:

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

另外,如果在JavaScript语句永远离开了周围的括号。

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"); 
} 

}); 
}); 
0

旁边已经提到的错误,试试这个。 把这两个班在你的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>