如何使用存储的 <td> 索引变量删除 HTML table 行

How to delete HTML table row with stored <td> index variable

我有一个网页列出了 table 的多行。每行都有一个按钮,用于在用户想要删除该行时打开确认模式。

有什么方法可以将行信息(索引或其他信息)传递给 table 元素之外的提交按钮元素并执行实际的删除功能?

我知道 <input type="button" value="Delete" onclick="deleteRow(this)"/> 如果它在 tr 元素内就可以解决问题,但事实并非如此。

我的HTML代码:

            <table id="myTable">
                <tr>
                    <th><fmt:message key="time"/></th>
                    <th><fmt:message key="name"/></th>
                </tr>
                <c:forEach items="${myList}" var="item">
                    <tr>
                        <td>${item.timeStamp}</td>
                        <td>${item.name}</td>
                        <td><input type="button" onclick="openModal"/>Delete</td> //here I want to store this rows index
                    <tr>
               </c:forEach>
            </table>
            <div class="modal-container" id="modal_container">
                <div class="modal">
                    <p>Do you want to remove item?</p>
                    <button type="button" id="close">Cancel</button>
                    <button type="submit" id="remove" onclick="deleteRow(this)">Yes</button> //here I want to use the stored index
               </div>
            </div>

我从未使用过 Jsp 但您可以尝试这样的操作(原版 javascript):

var form = window.querySelector('#myTable');
var buttonSubmit = window.querySelector('#remove'); 

// Events
buttonSubmit.addEventListener('click', submitMe);
form.addEventListener('submit', submitMe);

// Submit function
function submitMe(e) {
  e.preventDefault(); // 'Revoke' current action of the event (use to stop input submit request)
  const formData = new FormData(form);
  formData.append('CustomKey', 'CustomValue');
  // Send new XMLHttpRequest here
}

一些文档:

您需要全局变量来保存行:

var row;

然后是打开模态并保存行的函数:

// When the user clicks on the button, open the modal and save the row
let openModal = function(scope) {
  modal.style.display = "block";
  row = scope;
}

然后是用户按“是”时删除行的函数:

// When the user clicks on the yes button, delete the row, close the modal and reset row
function deleteRow() {
  var parent = row.parentNode.parentNode;
  parent.parentNode.removeChild(parent);
  row = "";
  modal.style.display = "none";
}

您的按钮应该会打开模态对话框

<td><input type="button" onclick="openModal(this)"/></td>

如果用户按“是”,您将调用删除功能

<!-- The Modal -->
<div id="myModal" class="modal">
  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Do you want to remove item?</p>
    <button type="submit" id="remove" onclick="deleteRow()">Yes</button>
  </div>
</div> 

我在我的 codepen 页面上为您解决了这个问题。