我正在做一个电子商务项目,对于发货部分,我让用户输入一个与价格相关的区域,然后用移除按钮显示这两个值。 用户可以生成这三个元素的多次。(在这三个生成的元素中的每一个,隐藏有两个输入来处理值,然后使用php处理该数据) 当点击删除按钮时,我想删除输入区域+价格+删除按钮的相似类名。 但是在动态生成时如何做到这一点? 这是HTML部分:
<label for="places">Places/area : </label>
<input type="text" name="ps_places" id="ps_places" value="" >
<label for="ps_price" "> Price : </label><input type="text" name="ps_price" id="ps_price" value="" >
<button type="button" onclick="ps_add()">OK</button>
<div id="display1"></div>
和javascript部分:
function addElement(parentId, elementTag, elementId, html) {
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('class', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function ps_add()
{
var pv = document.getElementById('ps_places').value;
var prv = document.getElementById('ps_price').value;
if((pv != "") && (prv != ""))
{
ps_id++;
addElement("display1", "span", ps_id, "- ");
addElement("display1", "label", ps_id, pv);
addElement("display1", "span", ps_id, " : ");
addElement("display1", "label", ps_id, prv);
addElement("display1", "span", ps_id, " ");
addElement("display1", "button", ps_id, "Remove");
addElement("display1", "br", ps_id, "");
var input1 = document.createElement("input");
input1.setAttribute("type", "hidden");
input1.setAttribute("class", "ps_id");
input1.setAttribute("name", "ps_places[]");
input1.setAttribute("value", pv);
display1.appendChild(input1);
var input2 = document.createElement("input");
input2.setAttribute("type", "hidden");
input2.setAttribute("class", "ps_id");
input2.setAttribute("name", "ps_price[]");
input2.setAttribute("value", prv);
display1.appendChild(input2);
}
document.getElementById('ps_places').value= "";
document.getElementById('ps_price').value= "";
}
答案 0 :(得分:3)
正如您添加jquery,我假设您使用jQuery。您可以使用以下命令删除所有元素的类名:
$(".classname").remove();
如果是错误的,并且您需要纯JavaScript解决方案,则可以使用:
elems = document.querySelectorAll(".classname");
for (var elem in elems)
elems[elem].parentNode.removeChild(elems[elem]);