今天看到一同学的贴子http://topic.csdn.net/u/20120717/10/51e85309-55e5-4f5a-bf0e-bef98c31ae23.html?seed=386935035&r=79147953#r_79147953,发现了常用的table中的一个误区,总结了一下
代码:
//创建任意类型tag
function make(tagname,attributes,children){
//如果参数的个数为二个,并且属性的类型是数组或是字符串,将当前的属性值赋给孩子
if(arguments.length == 2 && (attributes instanceof Array || typeof attributes == "string")){
children = attributes;
attributes = null;
}
//创建了一个元素
var e = document.createElement(tagname);
//为新标签设置属性
if(attributes) {
for(var name in attributes)
e.setAttribute(name, attributes[name]);
}
if(children != null){
if(children instanceof Array){
var parent = e;
for(var i = 0; i < children.length; i++){
var child = children[i];
if(typeof child == "string"){
child = document.createElement(child);
parent.appendChild(child);
parent = child;
}
}
}
else if(typeof children == "string"){
e.appendChild(document.createTextNode(children));
}
else
e.appendChild(children);
}
return e;
}
function show(e){
var f = make('table',{border:1,width:'200px',height:'300px'},['tbody','tr','td']);//这里的tbody是tr的父节点,不加tbody这个table就展示不出来,需要加我下面注释掉的那行
document.getElementById("divId").appendChild(f);
//document.getElementById("divId").innerHTML = document.getElementById("divId").innerHTML;
}
1.attributesinstanceofArray的运行结果为false attributes的值为{border:1,width:'200px',height:'300px'}
2.childreninstanceofArray为true
3.tr节点其实是tbody节点的子元素,如果不传入tbody则该table就显示不出来