2012-04-09 64 views
2

當我返回並擦除數據時,將輸入字段留空,但背景不會恢復爲原始顏色,除非我輸入A「0」。需要腳本通過輸入更改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> 
+1

你爲什麼第二次測試'.length'?這就是'else'的用途。 – Blazemonger 2012-04-09 13:57:45

回答

0

這一個應該工作...

<script> 

$(document).ready(function() { 

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

</script> 
+0

我不認爲'keypress'會爲OP所要做的事情工作。 – 2012-04-09 14:05:17

3

的問題是,因爲使用的是keypress執行鍵的動作之前被調用。如果您使用keyup這將工作:

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

此外,作爲@ mblase75指出的那樣,你不需要測試值的length在其他條件。

Example fiddle

如果您想進一步簡化這個代碼,你可以簡單地使用三元語句.val().length爲條件,作爲一個正整數,將等同於真:

$("#id").keyup(function() { 
    $(this).css("background-color", $(this).val().length ? "red" : "grey"); 
}); 
2

你會要使用keyup考慮到剛輸入的字符:

$(function(){ 
    $("#id").keyup(function() { 
     $("#in").css("background-color", $(this).val().length > 0 ? "red" : "grey"); 
    }); 
});​ 

這裏有一個jsFiddle來演示。

+0

您已將'this'用於'#in'和'#id'。 – Blazemonger 2012-04-09 14:04:47

+0

謝謝你指出。我已經更新了我的答案。 – 2012-04-09 14:06:25

-2

使用KEYUP

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

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

}); 
}); 
</script> 
+0

如果你投下來,請評論爲什麼投票下來。我在發佈之前測試了這個答案,它工作正常。 – 2012-04-09 18:10:38

0

在你的情況, '按鍵' 事件input.val()。長度改變之前調用。 你的代碼運行選擇器retreiving五次,insted之一。

看看這個代碼,它工作正常:

HTML:

<input id="id" type="text" autocomplete="off"> 
<div class="in"></div>​​​ 

CSS:

.in {width:200px; height:20px; background-color:#grey;} 
.in-red {background-color:red;} 

JS:

$(function(){ 
    var $in = $('.in'); 
    $('#id').on('keyup', function(){ 
     $this = $(this); 
     if ($this.val().length > 0) { 
      $in.addClass('in-red'); 
     } else { 
      $in.removeClass('in-red'); 
     } 
    }); 
});​ 

你可以測試它在http://jsfiddle.net/Qhkev/1/