2016-03-03 50 views
2
<asp:TextBox ReadOnly="true" ID="tbPhone" ClientIDMode="Static" runat="server" CssClass="tbStyle changeUpdate" Text=""></asp:TextBox> 
<asp:TextBox ReadOnly="true" ID="tbFax" ClientIDMode="Static" runat="server" CssClass="tbStyle changeUpdate" Text=""></asp:TextBox> 

$('#tbPhone, #tbFax').keypress(function() { //works 
    this.style.backgroundColor = "#BCFFB9"; 
}); 

我將有很多文本框,並希望爲每個文本框使用類,獲取ID並設置背景顏色。這將確保我可以爲所有文本框使用幾行代碼,而不管數字是多少。如何更改背景顏色使用一個類來定位控件的ID

所以我想這:

$(".changeUpdate").keypress(function() { 
    $(this).attr("id").style.backgroundColor = "#BCFFB9"; 
}); 

但我不斷收到此錯誤:

0x800a138f - Microsoft JScript runtime error: Unable to set value of the property 'backgroundColor': object is null or undefined 

我怎樣才能解決我的問題。

回答

5

你是那種混合Javascript和jQuery的語法,試試這個:

$(".changeUpdate").keypress(function() { 
    //$(this).attr("id").style.backgroundColor = "#BCFFB9"; 
    $(this).css("background-color","#BCFFB9"); 
}); 
+0

謝謝你的糾正。我知道我錯過了一些東西。 – Si8

1

你是不是正確選擇與類「changeUpdate」你的代碼的元素。 $(this).attr("id")獲取元素的ID,但不選擇它,這就是爲什麼存在未定義的引用錯誤。

用途:

// when the keypress event happens on an element with class changeUpdate 
$('.changeUpdate').keypress(function() { 

    // Select all elements with class changeUpdate and change the css attribute 'background-color' to the color specified 
    $('.changeUpdate').css('background-color', '#BCFFB9'); 
}); 

或使用$(this).css('background-color', '#BCFFB9');改變背景顏色剛好與按鍵的元素。

+0

謝謝你的回答。 – Si8