2012-04-09 73 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>