【发布时间】:2013-12-27 18:00:24
【问题描述】:
我有一个段落元素数组。单击每个<p> 时,我希望从DOM 中删除该元素。我编写的代码仅在元素由其 id 指定时才有效。我尝试使用 this 关键字,以及循环遍历元素但没有任何成功,如下面的代码所示。
我在这里做错了什么?我该如何克服它?
<div class="section" id='section2'>
<a name="section-two" href="#top">Section Two</a>
<p id='tester'>Text here <span><img src='images/remove.png' height='20px'/></span></p>
<p>Text here. <span><img src='images/remove.png' width='20px'/></span></p>
<p>Text here. <span><img src='images/remove.png' height='20px'/></span></p>
<p>Text here. <span><img src='images/remove.png' height='20px'/></span></p>
</div>
var section2 = document.getElementById('section2').getElementsByTagName('p');
for(var i = 0; i < section2.length; i++) {
section2[i].addEventListener('click', function() {
section2[i].parentNode.removeChild(section2[i]);
}, false);
}
【问题讨论】:
标签: javascript for-loop addeventlistener removechild