我正在尝试使用输入创建出现和消失的效果。当单选按钮为“否”时,该项目应该出现。当单选按钮为"is"时,该项目应该消失。到目前为止,我已经让该项目出现,但无法通过 DOM 将其删除。我已经包含了关于如何删除我注释掉的电子邮件的示例,但似乎无法删除 innerHTML 或输入。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : $";
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
alert("Added Text Box");
}
function myFunction2() {
alert("Removed Textbox and Input");
anchor = document.getElementById("label");
anchor.parentNode.removeChild(anchor);
anchor2 = document.getElementById("INPUT");
anchor2.parentNode.removeChild(anchor2);
//THIS WORKS TO REMOVE EMAIL.
//anchor3 = document.getElementById("emailP");
//anchor3.parentNode.removeChild(anchor3);
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" onclick="myFunction2()" />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<br>
<br>
<button>Submit</button>
</form>
</body>
</html>
最佳答案
它不起作用,因为行 anchor = document.getElementById("label");
和 anchor2 = document.getElementById("INPUT");
正在寻找id 为 label
和 input
的元素,但无法找到它们。这些实际上是标签名称。
您需要为您在第一个函数中创建的元素添加一个id:
label.setAttribute("id", "idForLabel");
x.setAttribute("id", "idForInput");
然后将第二个函数中的行更改为:
anchor = document.getElementById("idForLabel");
anchor2 = document.getElementById("idForInput");
关于javascript - 使用 DOM 删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32980814/