2016-03-03 48 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