按下按钮时隐藏或删除重复元素的单个实例

时间:2016-01-20 16:19:24

标签: jquery html show-hide

如果单击“关闭”类的按钮,如何删除/隐藏单个'bakant'元素?使用以下jsfiddle生成元素:https://jsfiddle.net/L4f7pjau/

<div class="shape" id="plan4_shape">
    <span class="bakkant"><input class="measures" id="plan4_width" placeholder="mm"/><span class="times"> &times;</span> <input class="measures" id="plan4_width" placeholder="mm"/></span>
    <span class="bakkant" id="bakkant"><input class="measures" id="plan4_width" placeholder="mm"/><span class="times"> &times;</span> <input class="measures" id="plan4_width" placeholder="mm"/><button class="close" value="close1">&times;</button></span>
    <button name="add_row" class="addrow" id="addrow4" onClick="addrow()">Add row</button>
</div>

3 个答案:

答案 0 :(得分:2)

简短回答(针对那些注意力不集中的人):

--volumes-from

现在回答完整的答案:

现有代码存在多个问题,因此我想引导您完成一些建议和工作演示:

  • 能够删除您克隆的项目是第一个问题。如果删除,则无法再添加任何记录。我建议您使用未存储在列表中的模板项。我使用一个未知类型的虚拟// Listen for bubbled click events, coming from delete buttons $('.shape').on('click', '.close', function() { // Remove the row closest to the delete button pressed $(this).closest('.bakkant').remove(); }); 块来保存模板的HTML。非常容易维护。

  • 此外,删除需要对动态添加的项进行操作,因此需要成为委托事件处理程序,连接到不变的祖先元素。我将它连接到script,因为这是所有记录的共同祖先。

  • 您还有.shape的重复ID,您在页面中无法拥有这些ID。让他们成为一个班级。

jQuery代码(已评论):

plan4_width

完成工作解决方案: https://jsfiddle.net/y52ttwfv/4/

说明:

  • 您还为每行上的指定了$(function() { // Your count of added IDs var i = 0; // Add button handler $('#addrow4').click(function() { // Get the template HTML and convert to an element var $clone = $($('#template').html()); // Set the id of the new entry (assuming it needs an ID) $clone.attr('id', "bakkant" + ++i); // Add the new row to the start of the container $('.shape').prepend($clone); }); // Listen for bubbled click events, coming from delete buttons $('.shape').on('click', '.close', function() { // Remove the row $(this).closest('.bakkant').remove(); }); }); 。一个应该是width

答案 1 :(得分:1)

我建议你将两个(bakkant和一个按钮)包裹在相同的div,span或你喜欢的内容中。

然后你可以找到一个按钮的父级并隐藏它,用按钮和bakkand这样隐藏div。

您可以使用.parent()查找div(jQuery API - parent()

和.hide()隐藏div。

答案 2 :(得分:1)

$(this).parent()将识别父级。

如果您要进一步嵌套按钮元素,请尝试$(this).closest('.bakknat')

然后使用.remove().hide()。如果您要提交表单并动态解析输入,则可能需要使用remove。

$(this).parent().remove();

这是另一个线程 .parent().remove() issue