如何在单击按钮时删除特定数量的 DOM 元素?

我想弄清楚如何在单击按钮时删除按钮上方最近的四个 div 元素(连同包含按钮的 div)。我一直在尝试使用.closest(),但运气不佳。我将始终删除按钮本身以及 DOM 顺序中按钮上方的四个元素。


下面有多组带有 div 的行,所以我不能单独按类选择这些元素。


示例 HTML:


//Row 1

<div class="col-2 selectedRow">014</div>

<div class="col-4 selectedRow">Test</div>

<div class="col-2 selectedRow">Special Charge</div>

<div class="col-2 selectedRow">012</div>

<div class="col-2 selectedRow"><input type="button" class="removeCode" value="Remove"></div>


//Row 2

<div class="col-2 selectedRow">012</div>

<div class="col-4 selectedRow">Test 2</div>

<div class="col-2 selectedRow">Other Charge</div>

<div class="col-2 selectedRow">011</div>

<div class="col-2 selectedRow"><input type="button" class="removeCode" value="Remove"></div>

Java脚本:


$("form").on('click', '.removeCode', function (event) {

    //Remove the current div container, and the 4 divs above that element in the DOM order.

});


拉丁的传说
浏览 109回答 1
1回答

largeQ

您需要对 HTML 文件进行更改,例如:input将您的元素替换为button并应用与 wrapper 相同的样式div。将单个行包围在容器中单击时删除单击按钮的容器例如:$("form .removeCode").click(function(event) {&nbsp; $(this).parent(".container").remove();});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form>&nbsp; <div class="container">&nbsp; &nbsp; <div class="col-2 selectedRow">014</div>&nbsp; &nbsp; <div class="col-4 selectedRow">Test</div>&nbsp; &nbsp; <div class="col-2 selectedRow">Special Charge</div>&nbsp; &nbsp; <div class="col-2 selectedRow">012</div>&nbsp; &nbsp; <button type="button" class="col-2 selectedRow removeCode">Remove</button>&nbsp; </div>&nbsp; </div>&nbsp; <div class="container">&nbsp; &nbsp; <div class="col-2 selectedRow">012</div>&nbsp; &nbsp; <div class="col-4 selectedRow">Test 2</div>&nbsp; &nbsp; <div class="col-2 selectedRow">Other Charge</div>&nbsp; &nbsp; <div class="col-2 selectedRow">011</div>&nbsp; &nbsp; <button type="button" class="col-2 selectedRow removeCode">Remove</button>&nbsp; </div></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript