![](/img/trans.png)
[英].remove() only removes the innerHTML NOT the entire tag like I want it to
[英]I want to remove only the parent tag I clicked
我的代码中有 3 个按钮。
一是添加更多文件。 ( .btn-plus
) 一种是删除添加的一种。 ( .btn-minus
) 一是重置文件。 ( .btn-reset
)
我可以使用( .btn-plus
)按钮添加更多输入。
我怎样才能在我添加的每个输入中只删除我单击的那个( .btn-plus
)?
$(".btn-plus").click(function(){ $('.board-box__attachments').prepend('<li><div class="th">files</div><div class="td"><input type="file"><button class="btn btn-minus"> - </button></div></li>'); return false; }) $(".btn-minus").click(function(){ $(this).nextUntil('li').remove() }) $(".btn-reset").click(function(){ $(".board-box__attachments input").value = ""; })
li { width: 60%; background: lightblue; list-style: none; padding: 0.5em; border-bottom: 1px solid white; }.th { width: 100px; float: left; }.td { width: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="board-box__attachments"> <li> <div class="th">files</div> <div class="td"> <input type="file"> <button class="btn btn-plus"> + </button> <button class="btn-reset">Reset</button> </div> </li> </ul>
您必须使用on()
将事件附加到动态添加的元素。 然后使用closest()
来查找当前单击元素的父元素。
$("body").on("click", ".btn-minus", function(){
$(this).closest('li').remove();
})
您的代码有两个问题:
btn-minus
的元素。 所以click
事件不起作用,你需要on
事件上使用。 $(".btn-minus").click(function(){
所以你需要使用而不是这个
$(document).on('click', '.btn-minus', function() {
$(this).closest('li').remove();
请查看更新的JSFiddle
$(this).nextUntil("li")
不匹配任何内容。 它只搜索this
的兄弟姐妹,并且该按钮没有任何li
兄弟姐妹。 如果要 select 包含按钮的li
,请使用$(this).closest("li")
。
您还需要使用事件委托将事件处理程序绑定到动态创建的元素。
$(".btn-plus").click(function(){ $('.board-box__attachments').prepend('<li><div class="th">files</div><div class="td"><input type="file"><button class="btn btn-minus"> - </button></div></li>'); return false; }) $(".board-box__attachments").on("click", ".btn-minus", function(){ $(this).closest("li").remove() })
li { width: 50%; background: lightblue; list-style: none; padding: 1em; border-bottom: 1px solid white; }.th { width: 100px; float: left; }.td { width: 100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="board-box__attachments"> <li> <div class="th">files</div> <div class="td"> <input type="file"> <button class="btn btn-plus"> + </button> </div> </li> </ul>
在这里您可以动态创建元素,因此一旦加载页面,浏览器就不会知道“.btn-minus”
尝试这个:
$(document).on('click', '.btn-minus', function(){
$(this).closest('li').remove()
})
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.