html dom操作

1、常用函数

createElement(targetName);//创建dom元素,参数为元素名 ,如input

setAttribute(attr,value);//给dom元素设置属性

appendChild(dom);//添加到父元素下

removeChild(dom);//删除dom元素

dom.childNodes;//获取dom的所有直接子元素

2、实例1:给div中添加一个input

<div id='div1'></div>

 

var div= document.getElementById('div1');

var obj = document.createElement("input"); //创建dom元素: input

obj.setAttribute("id","id1");//设置属性:给input设置id为id1

div.appendChild(obj);//添加到div中

div.childNodes;//返回数组,长度为1

3、实例2:点击添加按钮添加一行录入,删除则删除一行录入,如下图:


html dom操作
 

<table id='orgBed' style="width: 1000px;margin: auto;">
  <tr>
    <th style="text-align: center;">年份</th>
    <th style="text-align: center;">医师总人数</th>
    <th style="text-align: center;">床位数</th>
    <td><button type="button" class="btn btn-default btn-add" onclick="addOrgBed();">
          添加</button></td>
  </tr>
  <tr>
    <td><input class="form-control input-sm" name="dto.orgBed[0].year" id='year0'></input>
    </td>
    <td><input class="form-control input-sm" name="dto.orgBed[0].doctorCnt" id='doctor0'>
        </input></td>
    <td><input class="form-control input-sm" name="dto.orgBed[0].bedCnt" id='bed0'></input>
    </td>
  </tr>
</table>

 
 

/**
 * 点击添加一行dom事件
 */
function addOrgBed(){
	var table = document.getElementById('orgBed');
	var n = table.childNodes.length-1;
	var tr = document.createElement("tr");
	var td0 = document.createElement("td");
	var input0 =  document.createElement("input");
	input0.setAttribute("name", "dto.orgBed["+n+"].year");
	input0.setAttribute("id", "year"+n);
	input0.setAttribute("class", "form-control input-sm");
	var td1 = document.createElement("td");
	var input1 =  document.createElement("input");
	input1.setAttribute("name", "dto.orgBed["+n+"].doctorCnt");
	input1.setAttribute("id", "doctor"+n);
	input1.setAttribute("class", "form-control input-sm");
	var td2 = document.createElement("td");
	var input2 =  document.createElement("input");
	input2.setAttribute("name", "dto.orgBed["+n+"].bedCnt");
	input2.setAttribute("id", "bed"+n);
	input2.setAttribute("class", "form-control input-sm");
	var td3 = document.createElement("td");
	var a =  document.createElement("a");
	a.setAttribute("href", "#");
	//a.setAttribute("onclick", "deleteOrgBed("+n+");");
	a.setAttribute("onclick", "deleteOrgBed(this);");
	a.innerHTML = '删除';
	
	td0.appendChild(input0);
	td1.appendChild(input1);
	td2.appendChild(input2);
	td3.appendChild(a);
	tr.appendChild(td0);
	tr.appendChild(td1);
	tr.appendChild(td2);
	tr.appendChild(td3);
	table.appendChild(tr);
}
/**
 * 删除dom节点
 * @param obj:当前删除dom
 */
function deleteOrgBed(obj){
	var table = document.getElementById('orgBed');
	var tableChild = table.childNodes;
	for(var i=0;i<tableChild.length;i++){
		if(tableChild[i] == obj.parentNode.parentNode){
			table.removeChild(tableChild[i]);
			return;
		}
	}
}

相关推荐