代码改变世界

就地编辑

2012-02-17 21:26  边缘er  阅读(125)  评论(0)    收藏  举报
<div id="div1"></div>
<div id="div2"></div>
function addEvent( obj, type, fn ) {
if (obj.attachEvent){
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn](window.event);}
obj.attachEvent('on'+type, obj[type+fn]);
}else{
obj.addEventListener(type, fn, false);
}
}
//EditInPlaceField类
function EditInPlaceField(id, parent, value) {
this.id = id;
this.value = value || 'default value';
this.parentElement = parent;

this.createElements(this.id);
this.attachEvents();
};

EditInPlaceField.prototype = {
createElements: function(id) {
this.containerElement = document.createElement('div');
this.parentElement.appendChild(this.containerElement);

this.staticElement = document.createElement('span');
this.containerElement.appendChild(this.staticElement);
this.staticElement.innerHTML = this.value;

this.fieldElement = document.createElement('input');
this.fieldElement.type = 'text';
this.fieldElement.value = this.value;
this.containerElement.appendChild(this.fieldElement);

this.saveButton = document.createElement('input');
this.saveButton.type = 'button';
this.saveButton.value = '保存';
this.containerElement.appendChild(this.saveButton);

this.cancelButton = document.createElement('input');
this.cancelButton.type = 'button';
this.cancelButton.value = '取消';
this.containerElement.appendChild(this.cancelButton);

this.convertToText();
},
attachEvents: function() {
var that = this;
addEvent(this.staticElement, 'click', function() { that.convertToEditable(); });
addEvent(this.saveButton, 'click', function() { that.save(); });
addEvent(this.cancelButton, 'click', function() { that.cancel(); });
},

convertToEditable: function() {
this.staticElement.style.display = 'none';
this.fieldElement.style.display = 'inline';
this.saveButton.style.display = 'inline';
this.cancelButton.style.display = 'inline';

this.setValue(this.value);
},
save: function() {
this.value = this.getValue();
this.fieldElement.innerHtml = this.value;
this.convertToText();
/*var that = this;
var callback = {
success: function() { that.convertToText(); },
failure: function() { alert('Error saving value.'); }
};
ajaxRequest('GET', 'save.php?id=' + this.id + '&value=' + this.value, callback);
*/
},
cancel: function() {
this.convertToText();
},
convertToText: function() {
this.fieldElement.style.display = 'none';
this.saveButton.style.display = 'none';
this.cancelButton.style.display = 'none';
this.staticElement.style.display = 'inline';

this.setValue(this.value);
},

setValue: function(value) {
this.fieldElement.value = value;
this.staticElement.innerHTML = value;
},
getValue: function() {
return this.fieldElement.value;
}
};
//实例化
var aa = new EditInPlaceField('aa', document.getElementById('div1'), '第一个');
var bb = new EditInPlaceField('bb', document.getElementById('div2'), '第二个');