javascript - .removeChild() 不起作用

标签 javascript

我创建了一个可以添加的表单字段,但无法删除它。不知道为什么它不起作用,我想也许我传递了错误的参数?我尝试了很多变体。

<h3 class="color-text">What key fatures are you looking for?</h3>
<p class="contact-message">
    <textarea id="client-needs" placeholder="What key features are you looking to have within your website? ie. storefront, social media intigrtion, a blogging platform, content managment system, ect." name="client-needs" rows="5" cols="10"></textarea>
</p>


<script type="text/javascript">
var i = 1;
function addUrl(){
    if (i<3) {
        i++;
        var p = document.createElement('p');
        p.innerHTML = '<hr><textarea id="client-needs" placeholder="Add URL #'+i+'" name="client-needs'+i+'" rows="1" cols="10"></textarea><input type="button" value="Remove added URL" onclick="removeUrl(this)">';
        document.getElementById('examples').appendChild(p);

}
}

function removeUrl(textarea){
    document.getElementById('client-needs').removeChild(textarea.parentNode);
    i--;
}
</script>

<h3 class="color-text">Do you have and examples of what you want?</h3>
<p class="contact-message" id="examples">
    <textarea id="examples" placeholder="Do you know of any website like the one you want? ie. google.com, p5services.com, youtube.com" name="examples" rows="1" cols="10"></textarea>
</p>

<br>

<input type="button" value="Add url example" onclick="addUrl()">

最佳答案

removeChild 的使用不正确。要删除添加的段落内容,您应该执行以下操作:

function removeUrl(textarea) {
    textarea.parentNode.parentNode.removeChild(textarea.parentNode);
    i--;
}

textarea.parentNode 是要删除的 p 元素,而 textarea.parentNode.parentNode 是该段落的父元素,无论它是什么。应该在父级上调用 removeChild ,并且需要删除父级的子级。

演示:http://jsfiddle.net/7caysjw8/

关于javascript - .removeChild() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27207365/

相关文章:

javascript - AngularJS 指令中的 element.replaceWith

javascript - 如何在菜单按钮上运行不同文档中的功能

计算时出现 Javascript 错误

javascript - 随机播放来自多个框的 div

javascript - 如何将类组件转换为函数无状态组件?

javascript - 从客户端浏览器直接上传 Amazon S3 文件 - 私钥泄露

javascript - vite 中的 Node.js 核心模块作为 webpack 后备

javascript - jQuery 第一个类型为 click 的元素

php - 如何禁用默认 DHTML 日历中的前几天?

javascript - OpenLayers 中的 Flash 动画不是连续渲染的