function delete(){
let k = document.getElementsByClassName('row');
for(let i=0; i<k.length; i++)
{
if(k[i].hasChildNodes()){
k[i].removeChild(k[i].childNodes[2]);
}
}
}
<div id="table">
<div class="row">
<div class="column">1.1</div>
<div class="column">1.2</div>
<div class="column">1.3</div>
<div class="column">1.4</div>
<div class="column">1.5</div>
</div>
<div class="row">
<div class="column">2.1</div>
<div class="column">2.2</div>
<div class="column">2.3</div>
<div class="column">2.4</div>
<div class="column">2.5</div>
</div>
<div class="row">
<div class="column">3.1</div>
<div class="column">3.2</div>
<div class="column">3.3</div>
<div class="column">3.4</div>
<div class="column">3.5</div>
</div>
<div class="row">
<div class="column">4.1</div>
<div class="column">4.2</div>
<div class="column">4.3</div>
<div class="column">4.4</div>
<div class="column">4.5</div>
</div>
<div class="row">
<div class="column">5.1</div>
<div class="column">5.2</div>
<div class="column">5.3</div>
<div class="column">5.4</div>
<div class="column">5.5</div>
</div>
</div>
<div id="button">
<input type="button" onclick="delete()" value="delete">
</div>
嗨,我目前正试图在 removeChild() 方法的帮助下每隔一列删除一次。如果我删除所有列,我想保留一个,但控制台显然显示“Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'"
因为如果所有列都被删除,就没有更多的孩子了。
现在的问题:我怎样才能捕捉到这个错误;有没有类似的东西,if(!k[i].hasChildNodes())
或者如果没有更多的孩子,我怎么能告诉 if 语句只是 print('hello')