众所周知我们经常需要给页面的表单赋值或设置,有时候需要批量设置.
但是一些表单的赋值操作可能不一样,利用jquery或者其他工具可以统一解决这个问题
另外的办法就是把这些表单控件用一个类包装起来,然后提供统一的方法来调用,这样就可以直接操作这些包装类了.
下面是我的实现方法:
测试文件:test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="lib.js"></script>
<script type="text/javascript" src="FormView.js"></script>
<script>
// 测试
window.onload = function(){
var inputView = new FormInput('txt1');
inputView.setValue('world')
//alert("input value:"+inputView.getValue())
var formRadio = new FormRadio('radioId');
var items = [{value:'1',text:'男'},{value:'0',text:'女'}]
formRadio.setItems(items);
formRadio.setValue(0);
//alert("radio value:"+formRadio.getValue())
var fromCheckBox = new FormCheckBox('checkboxId');
var items2 = [{value:'1',text:'足球'},{value:'0',text:'篮球'},
{value:'2',text:'羽毛球'}]
fromCheckBox.setItems(items2);
fromCheckBox.setValue([1,2]);
//alert(fromCheckBox.getValue())
var select = new FormSelect('selectId');
var selectItems = [{value:0,text:'上海'},
{value:1,text:'北京'},{value:2,text:'天津'}];
select.setItems(selectItems);
select.setValue(1)
//alert("select value:"+select.getValue())
var formTextArea = new FormTextArea('textAreaId');
formTextArea.setValue("<b>hello world</b>");
//alert("textarea value:"+formTextArea.getValue());
var controls = [];
controls.push(inputView);
controls.push(formRadio);
controls.push(select);
controls.push(fromCheckBox);
controls.push(formTextArea);
// 这里实现了接口的统一
for(var i in controls) {
var control = controls[i];
alert(control.id + ": " + control.getValue())
}
}
</script>
</head>
<body>
input
<input id="txt1" value="hello"><br>
radio
<div id="radioId"></div><br>
checkbox
<div id="checkboxId"></div><br>
select
<select id="selectId"></select><br>
textArea
<textarea rows="3" cols="20" id="textAreaId"></textarea>
</body>
</html>
lib.js 这是一个工具类
;(function() {
var util = {
/**
* Usage:
*
* format('{y}年{m}月{d}日',{y:'2010',m:'09',d:'15'});
* return: 2010年09月15日
*/
format:function(str,obj){
for(var key in obj){
str = str.replace(new RegExp("\\{" + key + "\\}", "g"), obj[key]);
}
return str;
}
};
var lib = {
extend:function(subClass,superClass){
var F = function(){};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if(superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
/**
* 调用父类的构造函数
* @param subClass 子类函数名
* @param subInstance 子类对象引用
*/
,callSuper:function(subClass,subInstance){
var argsArr = [];
for(var i=2,len=arguments.length; i<len; i++) {
argsArr.push(arguments[i]);
}
subClass.superclass.constructor.apply(subInstance, argsArr);
}
/**
* 子类中调用父类的函数
* @param subClass 子类函数名
* @param subInstance 子类对象引用
* @param methodName 父类方法名
*/
,runSuperMethod:function(subClass,subInstance,methodName){
return subClass.superclass[methodName].call(subInstance);
}
};
lib.util = util;
///////////String tool///////////
/**
* Usage:
* var str = new JString();
* str.append('Hello').append('World');
* alert(str.toString());
*/
function JString(s){
this._strings = new Array;
if(s && typeof s === 'string') {
this._strings.push(s);
}
}
JString.prototype.append = function(s){
this._strings.push(s);
return this;
}
JString.prototype.toString = function(){
return this._strings.join("");
}
///////////////////////////////
/**
* 装载类库. e.g.
*
* window.com = window.com || {};
* com.abc = com.abc || {};
* com.abc.util = com.abc.util || {};
*
* installLib(com.abc.util,"util");
* var $util = com.abc.util.util;
* $util.extend();
*/
window.installLib = function(scope, declareName) {
scope[declareName] = lib;
}
window.JString = window.JString || JString;
})();
FormView.js 这里就是定义包装类的地方
// 注册工具类
installLib(window,'myLib');
var Class = myLib;
/**
* 所有控件的父类
*/
var FormControl = function() {
this._control = null;
}
FormControl.prototype.setControl = function(control) {
this._control = control;
}
FormControl.prototype.getControl = function() {
return this._control;
}
/**
* 所有具有value属性的父类
*/
var FormValue = function(id) {
Class.callSuper(FormValue,this);
this.id = id || '';
this.setControl($("#" + this.id));
}
Class.extend(FormValue,FormControl);
FormValue.prototype.setValue = function(val) {
this.getControl().val(val);
}
FormValue.prototype.getValue = function() {
return this.getControl().val();
}
/**
* 所有具有Items属性的父类
*/
var FormItems = function(id) {
Class.callSuper(FormItems,this,id);
this.items = [];
}
Class.extend(FormItems,FormValue);
/**
* 构建items
*/
FormItems.prototype.buildItems = function() {
var itemTemplate = this.getItemTemplate();
var html = [];
var items = this.getItems();
var util = Class.util;
for(var i=0,len=items.length;i<len;i++){
var item = items[i];
html.push(util.format(itemTemplate,this._buildBindData(item,i)))
}
this.getControl().html(html.join(''));
}
FormItems.prototype._buildBindData = function(item,i) {
var id = this.id + "_" + i,
name = this.id;
value = item.value,
text = item.text;
var obj = {};
obj.id = id;
obj.name = name;
obj.value = value;
obj.text = text;
return obj;
}
/**
* 抽象方法,需要子类实现
*/
FormItems.prototype.getItemTemplate = function(){};
FormItems.prototype.setItems = function(items) {
this.items = items;
this.buildItems();
}
FormItems.prototype.getItems = function(items) {
return this.items;
}
// input
var FormInput = function(id) {
Class.callSuper(FormInput,this,id);
}
Class.extend(FormInput,FormValue);
// radio
var FormRadio = function(id) {
Class.callSuper(FormRadio,this,id);
}
Class.extend(FormRadio,FormItems);
/**
* 重写父类的方法
*/
FormRadio.prototype.getItemTemplate = function() {
var jStr = new JString();
jStr.append('<input type="radio" id="{id}" name="{name}" value="{value}" />')
.append('<label for="{id}">{text}</label>');
return jStr.toString();
}
FormRadio.prototype.getValue = function() {
return this.getControl().find('input:checked').eq(0).val();
}
FormRadio.prototype.setValue = function(val) {
this.getControl().find('input[value='+val+']').attr('checked','checked');
}
// checkbox
var FormCheckBox = function(id) {
Class.callSuper(FormCheckBox,this,id);
}
Class.extend(FormCheckBox,FormItems);
/**
* 重写父类的方法
*/
FormCheckBox.prototype.getItemTemplate = function() {
var jStr = new JString();
jStr.append('<input type="checkbox" id="{id}" name="{name}" value="{value}" />')
.append('<label for="{id}">{text}</label>');
return jStr.toString();
}
FormCheckBox.prototype.getValue = function() {
var $checkboxes = this.getControl().find('input:checked');
var ret = [];
$checkboxes.each(function() {
ret.push(this.value);
});
return ret;
}
FormCheckBox.prototype.setValue = function(arr) {
var $div = this.getControl();
$div.find('input').attr('checked',false);
for(var i=0,len=arr.length;i<len;i++) {
$div.find('input[value='+arr[i]+']').attr('checked',true);
}
}
// select
var FormSelect = function(id) {
Class.callSuper(FormSelect,this,id);
}
Class.extend(FormSelect,FormItems);
/**
* 重写父类的方法
*/
FormSelect.prototype.getItemTemplate = function() {
var str = '<option value="{value}">{text}</option>';
return new JString(str).toString();
}
// textarea
var FormTextArea = function(id) {
Class.callSuper(FormTextArea,this,id);
}
Class.extend(FormTextArea,FormValue);
包装类的定义采用面向对象的方式,这样的设计思路把公共部分都抽取出来,有些控件只需声明一下就可以了.如:
var FormTextArea = function(id) {
Class.callSuper(FormTextArea,this,id);
}
Class.extend(FormTextArea,FormValue);
只要简单的两句,其它功能都封装在父类里面了