单击删除按钮时删除文本框,小时和文本

时间:2015-02-19 16:01:04

标签: javascript jquery

我想在删除按钮时删除通过文本框删除按钮水平线单击(如下图所示)。

enter image description here

到目前为止,我已尝试过以下操作,但它不起作用:

$(document).ready(function() {
    // Remove waypoints
    $(".remove-waypoint-button").click(function() {
        $(this).parent.closest('input').remove();
        $(this).parent.closest('hr').remove();
    });
});

Fiddle here

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

您需要使用prev()代替closest()

使用

// Remove waypoints
$(".remove-waypoint-button").click(function () {
    $(this).prev('input').remove();
    $(this).prev('hr').remove();
    $(this).remove();
});

DEMO

但是我建议你在div中包含输入和按钮,然后你可以使用.parent()一次删除所有内容。这是一个例子。



$(document).ready(function() {
  // Remove waypoints
  $(".remove-waypoint-button").click(function() {
    $(this).parent('div').remove();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="waypoints">
  <div>
    <input type="text" class="form-control booking waypoint input-lg" placeholder="Via" />
    <label class="remove-waypoint-button">Remove</label>
  </div>
  <div>
    <input type="text" class="form-control booking waypoint input-lg" placeholder="Via" />
    <label class="remove-waypoint-button">Remove</label>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

更好的方法是通过对类似字段进行分组来提高您的标记。

这也改善了脚本。

我希望这是你所期望的。

&#13;
&#13;
		$(function() {
		  $(".remove-waypoint-button").on("click", function() {
		    $(this).parent(".container").remove();
		  })
		});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="waypoints">
  <input type="text" class="form-control booking waypoint input-lg" placeholder="Via">
  <hr>
  <div class="container">
    <input type="text" class="form-control booking waypoint input-lg" placeholder="Via">
    <label class="remove-waypoint-button">Remove</label>
    <hr>
  </div>
  <div class="container">
    <input type="text" class="form-control booking waypoint input-lg" placeholder="Via">
    <label class="remove-waypoint-button">Remove</label>
    <hr>
  </div>
  <div class="container">
    <input type="text" class="form-control booking waypoint input-lg" placeholder="Via">
    <label class="remove-waypoint-button">Remove</label>
    <hr>
  </div>


</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

nearest()适用于元素的父元素。 hr和输入不是标签的父级。 感谢

相关问题