首先,用我们最简单的法子写个html页面:
var oDiv = document.createElement('div');
oDiv.id = 'box';
oDiv.alt = 'This is a div';
oDiv.style.color ='red';
oDiv.style.width ='1000px';
oDiv.style.margin ='0 auto';
oDiv.innerHTML = 'This is a div';
document.body.appendChild(oDiv);
毫无疑问,这是一个很简单的页面,接下来是用方法来改写上面的语句:
var oDiv = createEle();
attr(oDiv,{
id : 'box'
,title : 'This is a div'
,color : 'red'
,width : '1000px'
,margin: '0 auto'
});
oDiv.innerHTML = 'This is a div';
append(document.body,oDiv);
// function
function createEle(tag){
return document.createElement(tag || 'div');
}
function append(oParent,obj){
oParent.appendChild(obj);
}
function attr(obj,json){
for(var i in json){
if(
i == 'title'
|| i == 'id'
|| i == 'src'
|| i == 'alt')
{
obj[i] = json[i];
}else{
obj.style[i] = json[i];
}
}
}
可以根据逻辑关系,再更改下:
var oDiv = createEle(document.body
,{
id : 'box'
,title : 'This is a div'
,color : 'red'
,width : '1000px'
,margin: '0 auto'
}
);
oDiv.innerHTML = 'This is a div';
// function
function createEle(oParent,json,tag){
var obj = document.createElement(tag || 'div');
if(oParent){
append(oParent,obj);
}
if(json){
attr(obj,json);
}
return obj;
}
function append(oParent,obj){
oParent.appendChild(obj);
}
function attr(obj,json){
for(var i in json){
if(
i == 'title'
|| i == 'id'
|| i == 'src'
|| i == 'alt')
{
obj[i] = json[i];
}else{
obj.style[i] = json[i];
}
}
}