您的位置:首页 > Web前端 > JavaScript

JS DOM 基础

2013-12-24 15:24 302 查看
1.DOM 的4个基本接口

  Document  Node  NodeList  NamedNodeMap

2.DOM 基本对象

  (1)Document 对象

  (2)Node 对象

    nodeType 属性返回节点的类型:Element(1)、Attr(2)、Text(3)、Comment(8)、Document(9)、DocumentFragment(11)

  (3)NodeList 对象

  (4)Elment 对象

  (5)Attr 对象

3.判断文本是否空格的方法:

    if(node.nodeType == 3 && !/\s/.test(node.nodeValue)){...}

4.DOM操作综合实例。

  本案例中,要实现添加和删除分类信息,主要用到创建节点、插入节点、删除节点、设置元素节点属性等操作。运行效果及代码如下。



按 Ctrl+C 复制代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>domdemo</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="javascript" type="text/javascript">
var id = 0;
function addSort(){
var txtInput = document.getElementById("txt");
if(txtInput.value == ""){
alert("请输入分类名称!");
txtInput.focus();
return;
}
var row = document.createElement("tr");
var rowId = id;
row.setAttribute("id",rowId);
row.bgColor="#99FF99";
var cell = document.createElement("td");
cell.bgColor="#6699CC";
var txtNode = document.createTextNode(txtInput.value);
cell.appendChild(txtNode);
row.appendChild(cell);

var deleteButton = document.createElement("input");
deleteButton.setAttribute("type","button");
deleteButton.setAttribute("value","删 除");
deleteButton.onclick = function(){deleteSort(rowId)};
cell = document.createElement("td");
cell.appendChild(deleteButton);
row.appendChild(cell);

document.getElementById("sortList").appendChild(row);
txtInput.value = "";

id++;
}

function deleteSort(id){
if(null != id){
var rowToDelete = document.getElementById(id);
var sortList = document.getElementById("sortList");
sortList.removeChild(rowToDelete);
}
}
</script>
</head>

<body>
<table border="1" width="80%" align="center" bgColor="#99ccff">
<tbody>
<tr>
<td colspan="3" align="center"><b>分类管理</b></td>
</tr>
<tr>
<td>请输入分类名称:</td>
<td><input id="txt" type="text" size="40"/></td>
<td><input id="addBtn" type="button" value="添加" onclick="addSort()"/></td>
</tr>
<tr>
<td colspan="3" align="center"><b>已添加的分类</b></td>
</tr>
</tbody>
</table>
<table border="1" align="center" width="80%">
<tr height="30">
<td width="80%">分类名称</td>
<td>操作</td>
</tr>
<tbody id="sortList"></tbody>
</table>
</body>
</html>
按 Ctrl+C 复制代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: