-2 javascript forms jquery reference object
我希望将一些选项作为对象传递给我的jQuery插件.我是这样做的:
$("#contact-form").formValidate({
contactname: {
"minLength": 5
},
contactemail : {
"minLength": 4
},
contactsubject : {
"minLength": 10
},
contactmessage : {
"minLength": 25
}
});
Run Code Online (Sandbox Code Playgroud)
在我的函数中,我想用字符串引用对象,该字符串是表单字段的输入id.
$.fn.formValidate = function(options) {
//...
var $this = $(this);
var id = $this.attr("id");
var length = options.id.minLength;
//...
}
Run Code Online (Sandbox Code Playgroud)
此解决方案不起作用.
//编辑
(function($, window, document, undefined ) {
$.fn.formValidate = function(options) {
/*
* Deafults values for form validation.
*/
var defaults = {
minLength: 5,
type : "text",
required : true
};
var methods = {
error : function(id) {
$(id).css("border", "1px solid red");
}
}
var settings = $.extend({}, defaults, options);
console.log(options);
this.children().each(function() {
var $this = $(this);
var tagName = $this[0].nodeName;
var inputType = $(this).attr("type");
var id = $this.attr("id");
console.log(id);
var property = options[id].minLength;
if (tagName == "INPUT") {
console.log("property: " + property);
console.log("--------------------------");
$(this).keyup(function() {
if ($this.val().length > 0) {
$this.css("border", "1px solid red");
} else {
$this.css("border", "1px solid #ccc");
}
});
}
});
return this;
};
}(jQuery));
Run Code Online (Sandbox Code Playgroud)
表单options.id.minlength访问一个名称为字符串文字"id"的属性.
相反,您需要options[id].minlength访问属性的表单,该属性的名称是变量的值id.
此外,id可能没有您认为它具有的价值.由于$this似乎是#contact-form的引用,因此id将具有值"contact-form".如果要访问表单中的元素集合,请尝试类似的方法$this.find('input,textarea,select').
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |