我正在编写一个基本的 jQuery 表单验证脚本,并且发生了类似的事情:
(请注意,我已经简化了验证标准,因为这不是这里的问题。)
$('#contact-form').submit( function (event) {
event.preventDefault();
var name = $(this).find('input[type="text"]').val();
var message = $(this).find('textarea').val();
// Validation
if (name.length <= 3 || message.length <= 3) {
$(this).after('<span>Error<span>');
}
});
我要做的就是如何让 jQuery 识别语句中发生错误的正确 this
if (name.length <= 3 || message.length <= 3) {
$(this).after('<span class="error">Error<span>');
}
并插入其后的误差跨度。我目前所拥有的仅在第一个输入之后插入错误消息,而不是在有错误的输入之后插入错误消息。
如果我将每个元素验证分开在自己的 if 语句中,我知道该怎么做,但我认为这将是不必要的重复。
另外,请不要建议任何验证插件,我知道这些,但我想学习自己做到这一点。
谢谢。
I am writing a basic jQuery form validation script and I have something like this going on:
(Please note, I have simplified the validation criteria since it is not the problem here.)
$('#contact-form').submit( function (event) {
event.preventDefault();
var name = $(this).find('input[type="text"]').val();
var message = $(this).find('textarea').val();
// Validation
if (name.length <= 3 || message.length <= 3) {
$(this).after('<span>Error<span>');
}
});
What I wnat to do is somhow make jQuery recognize the corect this where the error has ocured from the
if (name.length <= 3 || message.length <= 3) {
$(this).after('<span class="error">Error<span>');
}
statement and insert the error span after it. What I currently have inserts the error message only after the first input, not the input that had a mistake.
I know how to do it if I separate each element validation in its own if statement, but I think that would be unnecessary repetition.
Also please don't suggest any validation plugins, I am aware of those, but I want to learn to do this on my own.
Thank you.
发布评论
评论(3)
jquery 中的 this 指的是生成事件的元素:在您的情况下
$(this)
指的是 id = 'contact.form' 的元素。你可以这样做:
This in jquery refers to the element that generated the event: in your case
$(this)
refers to the element with id = 'contact.form'.You could do something like this:
大多数插件执行此操作的方式是使用一个描述每个输入的验证规则的类,例如
可以告诉脚本该字段是必需的并且它必须包含一个字符串。
然后,您可以使用类似
$('form input').each( function(n) { // code here });
这样$(this)
将引用在循环的每次迭代中输入有问题的输入字段。希望有帮助
The way that most of the plugins do this is to use a class which describes the validation rule for each input for example
<input name="name" value="" class="val-required val-string">
could tell the script that the field is required and that it must contain a string.You can then use something like
$('form input').each( function(n) { // code here });
this way$(this)
will refer to the input field in question at each iteration of the loop.Hope that helps
也许是这样的:
基本上,您需要使用
each()
来迭代您正在验证的元素。这将为您传递的每个元素调用一次您提供的each()
函数。每个函数调用都会将this
设置为当前正在迭代的元素。Perhaps something like:
Basically, you need to use
each()
to iterate over the elements you are validating. This will invoke the function that you provideeach()
once for each element that you pass. Each function invocation will havethis
set to the current element being iterated.