好的,我已经解决了您的问题。您不需要.parent() 或.closest()。您只需要保留对顶级容器的引用,然后根据所单击按钮上的 id 提取,您可以简单地删除以该 id 号结尾的容器的所有子项。
这就是我所做的:
$('#AddCC').click(function () {
uniqueId++;
var container = $("#CCcontainer"),
copyDiv = $("#CCPanel").clone(),
divID = "CCPanel" + uniqueId,
removeID = "RemoveCard" + uniqueId;
copyDiv.attr('id', divID);
container.append(copyDiv);
container.append("<div id =" + removeID + " ><div class =\"form-group col-sm-10\"></div><div class =\"form-group col-sm-2\"><button id=\"btn" + removeID + "\" type=\"button\" class=\"btn btn-warning form-control\">Remove Card</button></div></div>");
$('#' + divID).find('input,select').each(function () {
$(this).attr('id', $(this).attr('id') + uniqueId);
});
$("#" + removeID).find("button").on("click", function () {
var id = $(this).attr("id").replace("btnRemoveCard", "");
container.find("div[id$='" + id + "']").remove();
});
});
更新
fiddle 现在已更新为包含将保存所用面板的唯一 ID 的代码。它包括一个隐藏的输入字段,它简单地存储了一个 id 数组。它默认为 1,因为第一个面板已经在屏幕上。
<input id="hiddenStoredPanelsArray" type="hidden" value="[1]" />
在更新的 JavaScript 中,您会注意到我在其中留下了 console.log 语句,因此您可以在添加和删除面板时看到数组发生了什么。
$('#AddCC').click(function () {
uniqueId++;
var container = $("#CCcontainer"),
hidden = $("#hiddenStoredPanelsArray"),
storedPanels = hidden.length ? $.parseJSON(hidden.val()) : null,
copyDiv = $("#CCPanel").clone(),
divID = "CCPanel" + uniqueId,
removeID = "RemoveCard" + uniqueId;
console.log(storedPanels);
storedPanels.push(uniqueId);
hidden.val(JSON.stringify(storedPanels));
console.log(storedPanels);
copyDiv.attr('id', divID);
container.append(copyDiv);
container.append("<div id =" + removeID + " ><div class =\"form-group col-sm-10\"></div><div class =\"form-group col-sm-2\"><button id=\"btn" + removeID + "\" type=\"button\" class=\"btn btn-warning form-control\">Remove Card</button></div></div>");
$('#' + divID).find('input,select').each(function () {
$(this).attr('id', $(this).attr('id') + uniqueId);
});
$("#" + removeID).find("button").on("click", function () {
var id = parseInt($(this).attr("id").replace("btnRemoveCard", "")),
hidden = $("#hiddenStoredPanelsArray"),
storedPanels = hidden.length ? $.parseJSON(hidden.val()) : null,
index = storedPanels == null ? -1 : storedPanels.indexOf(id);
console.log(storedPanels);
if (index > -1)
storedPanels.splice(index, 1);
console.log(storedPanels);
container.find("div[id$='" + id.toString() + "']").remove();
hidden.val(JSON.stringify(storedPanels));
});
});