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