2011-11-03 66 views
0
<input id="aaa1" value="vvv"> 
<input id="aaa2" value=""> 
<input id="aaa3" value="ooo"> 
<input id="aaa4" value=""> 
<input id="aaa5" value="ooo"> 
<input id="aaa6" value="ooo"> 

if($('input[id^="aaa"]').val().length == 0){ 
    $('input[id^="aaa"]').css('background-color', 'red'); 
} 

$("#aaa1").live("click", function(){ 
    $(this).after("<input id='aaax' value='ooo'>"); 
}); 

爲什麼這隻適用於第一次輸入?如果第一個輸入值爲null,則爲所有輸入添加css。 我怎樣才能分開爲所有輸入?我使用也起到活() - 我還想添加了這個新的輸入jQuery中的selector ^如何?

活生生的例子:http://jsfiddle.net/Zm5jp/1/

回答

2

您需要遍歷使用each匹配inputs;

$('input[id^="aaa"]').each(function() { 
    var self = $(this); 

    if (self.val().length == 0) { 
     self.css('background-color', 'red'); 
    } 
} 

正如在docs for val();

獲取匹配元素集合中第一個元素的當前值。

I.e.您的代碼翻譯爲「如果第一個輸入值爲空,則爲所有元素設置後臺CSS」

+0

PS。可以使用'this.value'更高效地寫入'self.val()'。 –

2

val獲取匹配的第一個元素的設置值。你必須iterate over the set

$('input[id^="aaa"]').each(function() { 
    if($(this).val().length == 0) { 
     $(this).css('background-color', 'red'); 
    } 
});