日期:2014-05-16 浏览次数:20442 次
/*
* 就地编辑器实例
*/
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.fieldElemtnt = document.createElement("input");
this.fieldElemtnt.type = "text";
this.fieldElemtnt.value = this.value;
this.containerElement.appendChild(this.fieldElemtnt);
this.saveButton = document.createElement("input");
this.saveButton.type = "button";
this.saveButton.value = "Save";
this.containerElement.appendChild(this.saveButton);
this.cancelButton = document.createElement("input");
this.cancelButton.type = "button";
this.cancelButton.value = "Cancel";
this.containerElement.appendChild(this.cancelButton);
this.convertToText();
},
attachEvents : function(){
var that = this;
//运行到这里监听事件不起作用了
addEventListener(this.staticElement,"click",function(){
that.convertToEditable();
});
addEventListener(this.saveButton,"click",function(){
that.save();
});
addEventListener(this.cancelButton,"click",function(){
that.cancel();
});
},
convertToEditable : function(){
this.staticElement.style.display = "none";
this.fieldElemtnt.style.display = "inline";
this.saveButton.style.display = "inline";
this.cancelButton.style.display = "inline";
this.setValue(this.value);
},
save : function(){
this.value = this.getValue();
var that = this;
var callback = {
success : function(){
that.convertToText();
},
failure : function(){
alert("Error saving value.");
}
};
//ajaxRequest('Get',"url",callback);
},
cancel : function(){
this.convertToText();
},
convertToText : function(){
this.staticElement.style.display = "inline";
this.fieldElemtnt.style.display = "block";
this.saveButton.style.display = "block";
this.cancelButton.style.display = "block";
this.setValue(this.value);
},
setValue : function(value){
this.fieldElemtnt.value = value;
this.staticElement.innerHTML = value;
},
getValue : function(){
return this.fieldElemtnt.value;
}
}
$(function(){
var titleClassical = new EditInPlaceField("titleClassical",$("#doc").get(0),"Title Here");
var currentTitleText = titleClassical.getValue();
})
<body>
<div id="doc"></div>
</body>