我這樣寫第二個(gè)h1元素第一次執(zhí)行刪不掉,是為什么
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標(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ù)
? for(var i=0;i<content.childNodes.length;i++){
? ? ? if(content.childNodes[i].nodeType!=1){
? ? ? ? ? continue;
? ? ? }else{
? ? ? ? ? content.removeChild(content.childNodes[i]);
? ? ? }
? }
}
</script>
<button onclick="clearText()">清除節(jié)點(diǎn)內(nèi)容</button>
</body>
</html>
2018-11-29
這邊控制臺(tái)上報(bào)錯(cuò)“Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'”,然后單獨(dú)打印nodeType時(shí),php的h1顯示為3也就是#text類型。
個(gè)人建議使用while循環(huán)
while (content.childNodes.length > 0) {
? ? ? ? content.removeChild(content.firstChild);
}
只要有子節(jié)點(diǎn),就刪除第一個(gè)子節(jié)點(diǎn)