点评:通过JavaScript可以删除所有节点,本文里主要讨论 removeChild 函数,大家可以看看下面的示例
假设div里有这么些内容:复制代码
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=GBK">
<title>iScroll demo: simple</title>
<script type="text/javascript">
function deleteData(){
}
</script>
<style type="text/css" media="all">
body,ul,li {
padding:0;
margin:0;
border:0;
}
body {
font-size:12px;
-webkit-user-select:none;
-webkit-text-size-adjust:none;
font-family:helvetica;
}
</style>
</head>
<body>
<div ><input type="submit" value="删除li节点" /> </div>
<div >
<ul>
<li>Pretty row 1</li>
<li>Pretty row 2</li>
<li>Pretty row 3</li>
<li>Pretty row 4</li>
<li>Pretty row 5</li>
<li>Pretty row 6</li>
<li>Pretty row 7</li>
<li>Pretty row 8</li>
<li>Pretty row 9</li>
<li>Pretty row 10</li>
<li>Pretty row 40</li>
</ul>
</div>
</body>
</html>
复制代码
代码如下:
function deleteData(){
var el = document.getElementById('thelist');
var liNodes = document.getElementsByTagName("li");
alert(liNodes.length);
for(var i = 0; i < liNodes.length; i++){
alert("删除"+i+" liNodes[i]="+ liNodes[i]);
el.removeChild(liNodes[i]);
//<-- el.removeChild(liNodes[i]);
}
}
复制代码
代码如下:
function deleteData(){
var el = document.getElementById('thelist');
var liNodes = document.getElementsByTagName("li");
alert(liNodes.length);
for(var i = liNodes.length-1; i >=0; i--){
alert("删除"+i+" liNodes[i]="+ liNodes[i]);
el.removeChild(liNodes[i]);
//<-- el.removeChild(liNodes[i]);
}
}
复制代码
代码如下:
function deleteData() {
var el = document.getElementById('thelist');
var liNodes = document.getElementsByTagName("li");
alert(liNodes.length);
for (var i=0;i<el.childNodes.length;i++){
var childNode = el.childNodes[0]; //总是删除第一个,是不是更简单
el.removeChild(childNode);
}
}
复制代码
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=GBK">
<title>iScroll demo: simple</title>
<script type="text/javascript">
function initData(){
var el = document.getElementById('thelist');
var liNodes = document.getElementsByTagName("li");
alert(liNodes.length);
for(var i = liNodes.length-1; i >=0; i--){
alert("删除"+i+" liNodes[i]="+ liNodes[i]);
el.removeChild(liNodes[i]);
//<-- el.removeChild(liNodes[i]);
}
}
</script>
<style type="text/css" media="all">
body,ul,li {
padding:0;
margin:0;
border:0;
}
body {
font-size:12px;
-webkit-user-select:none;
-webkit-text-size-adjust:none;
font-family:helvetica;
}
</style>
</head>
<body>
<div ><input type="submit" value="删除li节点" /> </div>
<div >
<ul>
<li>Pretty row 1</li>
<li>Pretty row 2</li>
<li>Pretty row 3</li>
<li>Pretty row 4</li>
<li>Pretty row 5</li>
<li>Pretty row 6</li>
<li>Pretty row 7</li>
<li>Pretty row 8</li>
<li>Pretty row 9</li>
<li>Pretty row 10</li>
<li>Pretty row 40</li>
</ul>
</div>
</body>
</html>
新闻热点
疑难解答