[英]jQuery get parameters from class and use them on functions
I have two bits of code: a form and a jQuery function. 我有两段代码:表单和jQuery函数。
My problem is that I would like to get class attributes and use them on the form validation function. 我的问题是我想获取类属性并在表单验证功能上使用它们。 I am using Validity JS for validation. 我正在使用Validity JS进行验证。
This is what I have: 这就是我所拥有的:
<input type="text" name="name" value="" id="field_01" class=".require().minLength(5)" />
and in the JS function: 并在JS函数中:
var checks_to_apply = $("#field_01").attr("class").split(" "),
i, l;
var checks = "";
for (i = 0, l = checks_to_apply.length; i < l; i++) {
checks += checks_to_apply[i];
}
$("#field_01")+checks;
...
...
The right behaviour here is not respected. 这里没有正确的行为。
This is what I get from a "checks" alert: 这是我从“检查”警报中得到的结果:
.require().minLength(5)
but executing in that way it is not the same as doing it directly in the jQuery function like: 但是以这种方式执行与直接在jQuery函数中执行不同,例如:
$("#field_01").require().minLength(5);
Where am I wrong, I think that the problem in the method may be because it is seeing .require().minLength(5)
as a string and not as jQuery code to execute. 我在哪里错了,我认为方法中的问题可能是因为它将.require().minLength(5)
视为字符串而不是要执行的jQuery代码。
Any idea on how to fix it, please? 请问如何解决该问题?
as you are executing these functions on a particular object you would need to create the whole argument as an string and execute it via eval(): 当您在特定对象上执行这些功能时,您需要将整个参数创建为字符串并通过eval()执行:
var checks_to_apply = $("#field_01").attr("class").split(" "),
i,
l;
var checks = "$('#field_01')";
for (i = 0, l = checks_to_apply.length; i < l; i++) {
checks += checks_to_apply[i];
}
eval(checks);
But i would advise you to use a different validation plugin, because you are misusing the class attribute: Check out http://jquery.bassistance.de/validate/demo/ for a much better and cleaner annotation. 但我建议您使用其他验证插件,因为您滥用了class属性:请查看http://jquery.bassistance.de/validate/demo/,以获得更好更好的注释。
Most probably you want something like this 很可能你想要这样的东西
Firstly change here class="require minLength" minlengthdata="5"
首先在这里更改class="require minLength" minlengthdata="5"
var classes = $('#field_01').attr('class').split(" ");
var data = $('#field_01').attr('minlengthdata');
for (i = 0, i < classes ; i++) {
if(classes[i] == 'require'){
alert('its a requred field');
}
if(classes[i] == 'minLength' && data > 0){
alert('minimum value required');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.