我想将几个选项作为对象传递给我的 jQuery 插件。我就是这样做的:
$("#contact-form").formValidate({
contactname: {
"minLength": 5
},
contactemail : {
"minLength": 4
},
contactsubject : {
"minLength": 10
},
contactmessage : {
"minLength": 25
}
});
在我的函数中,我想使用作为表单字段输入 id 的字符串来引用对象。
$.fn.formValidate = function(options) {
//...
var $this = $(this);
var id = $this.attr("id");
var length = options.id.minLength;
//...
}
此解决方案不起作用。
//编辑
(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));