使用相同的代码向jQuery中的两个输入字段添加提示文本
我有一个使用相同的代码向jQuery中的两个输入字段添加提示文本,jquery,html,Jquery,Html,我有一个input字段,我使用jQuery添加了提示文本(这里HTML5placeholder不是一个选项) 它符合我的要求,就像这样: $("#reportMailerCustomFrom").change( function() { if ($("#reportMailerCustomFrom").val() == "") { $("#reportMailerCustomFrom").css("color", "#999");
input
字段,我使用jQuery添加了提示文本(这里HTML5placeholder
不是一个选项)
它符合我的要求,就像这样:
$("#reportMailerCustomFrom").change(
function() {
if ($("#reportMailerCustomFrom").val() == "") {
$("#reportMailerCustomFrom").css("color", "#999");
$("#reportMailerCustomFrom").val("required");
}
}).click(
function() {
if ($("#reportMailerCustomFrom").val() == "required") {
$("#reportMailerCustomFrom").val("");
$("#reportMailerCustomFrom").css("color", "#355F85");
}
}).blur(
function() {
if ($("#reportMailerCustomFrom").val() == "") {
$("#reportMailerCustomFrom").val("required");
$("#reportMailerCustomFrom").css("color", "#999");
}
});
我想用第二个输入
字段来实现这一点,但我不想复制所有代码,而只是简单地将reportMailerCustomFrom
更改为reportMailerCustomSubject
我尝试过使用$(“#reportMailerCustomFrom,#reportMailerCustomSubject”)
组合使用这个
关键字,但没有效果
最好的方法是什么 试试看
$("#reportMailerCustomFrom, #reportMailerCustomSubject").on('change blur', function () {
var $this = $(this);
if ($this.val() == "") {
$this.css("color", "#999");
$this.val("required");
}
}).click(function () {
var $this = $(this);
if ($this.val() == "required") {
$this.val("");
$this.css("color", "#355F85");
}
});
演示:这里是一个使用类的示例,这样无论有多少字段,您都不必更改jquery上的选择器(而且它不会因为多个ID而失控)
$(“.validateme”).change(
函数(){
如果($(此)==“”){
$(this.css(“color”和“#999”);
$(此).val(“必需”);
}
}).点击(
函数(){
if($(this.val()==“必需”){
$(此).val(“”);
$(this.css(“color”,“ţ355F85”);
}
}).模糊(
函数(){
if($(this).val()==“”){
$(此).val(“必需”);
$(this.css(“color”和“#999”);
}
});
看起来不错,继续,并将其标记为答案。像个白痴一样,我没有把“$”放在这个旁边。我脑子里有Java风格。将其作为答案发布您可以通过使用.on()
组合change
和blur
的处理程序来进一步简化它。
<input id="reportMailerCustomFrom" class="validateme" type="text"></input>
<input id="reportMailerCustomSubject" class="validateme" type="text"></input>
$(".validateme").change(
function() {
if ($(this) == "") {
$(this).css("color", "#999");
$(this).val("required");
}
}).click(
function() {
if ($(this).val() == "required") {
$(this).val("");
$(this).css("color", "#355F85");
}
}).blur(
function() {
if ($(this).val() == "") {
$(this).val("required");
$(this).css("color", "#999");
}
});