請(qǐng)教大神解答?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無(wú)標(biāo)題文檔</title>
</head>
<body>
<div id="content">
? <h1>html</h1>
? <h1>php</h1>
? <h1>javascript</h1>
? <h1>jquery</h1>
? <h1>java</h1>
</div>
<script type="text/javascript">
function clearText() {
? var content=document.getElementById("content");
? // 在此完成該函數(shù)
?
? //法一,一次性清除節(jié)點(diǎn)內(nèi)容
? for(var i=0;i<content.childNodes.length;i++){
????? if(content.childNodes[i].nodeType!=1){??
???????? continue;?
????? }else{
???????? content.removeChild(content.childNodes[i]);???
????? }
????????
????? }
請(qǐng)問(wèn)為什么要content.childNodes[i].nodeType!=1
2016-07-24
這里nodeType的返回值不為1就是說(shuō)它沒(méi)有元素在里面,就不用管它的,就繼續(xù)遍歷后面的節(jié)點(diǎn),當(dāng)nodeType返回值為1的時(shí)候就是說(shuō)這個(gè)節(jié)點(diǎn)下面還有元素,就需要remove掉。