Jquery 需要在下一个最近的类中显示错误消息,具体取决于输入

Jquery need to show error message in the next nearest class, depending on input

这里是例子http://jsfiddle.net/y53cd3qd/

有多种输入形式。每个输入表单旁边都有 spanclass="numeric".

<input type="text" id="miles_per_gallon" class="numeric" >
<span class="errmsg" style="color:red"></span>
<br/>

<input type="text" id="mileage" >
<span class="errmsg" style="color:red"></span>
<br/>

没有父元素 div 或其他元素

想要。如果用户键入的不是数字,则在最近或最近的 nex class="errmsg"

中显示错误

尝试过

$(".numeric").keypress(function (e) {

if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//$(".errmsg").html("Digits Only").show().fadeOut("slow");
$(this).siblings(".errmsg").html("hmm");
//alert("Digits only");
return false;
}

});

但在所有 class="errmsg" 中显示错误消息。如何只在下一个最近显示?

使用这个:

$(this).next(".errmsg").html("hmm");

$(".numeric").keypress(function (e) {
//if the letter is not digit then display error and don`t type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
//$(".errmsg").html("Digits Only").show().fadeOut("slow");
$(this).next(".errmsg").html("hmm");
//alert("Digits only");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="span_left">Miles per gallon<span class="required">*</span>: </span>
<input style="width:145px;" type="text" name="miles_per_gallon" id="miles_per_gallon" class="numeric" placeholder="Miles per gallon" value="" >
<span class="errmsg" style="color:red"></span>
<br/>

<span class="span_left">Mileage<span class="required">*</span>: </span>
<input style="width:145px;" type="text" name="mileage" id="mileage" value="" placeholder="Mileage" ><span class="errmsg" style="color:red"></span>
<br/>

我刚刚改成如下,

$(this).siblings(".errmsg").html("hmm"); 
to 
$(this).next(".errmsg").html("hmm");

看看这个。