javascript - 如何通过单击文本提交从循环生成的许多表单之一
问题描述
一个查询返回一个通知数组,这些通知在前端循环。对于数组中的每个项目,我有两个选项:Mark as read
, Delete
,每个都是文本。目标是通过单击文本来触发表单提交。
正在循环的前端代码是一个带有选项下拉列表的按钮。我希望能够单击文本以提交表单。我学过的 JavaScript 很棘手。我有两种方法可以获得点击响应,但我被卡住了,因为我不知道如何提交表单。
<button class="btn btn-light btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Action
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<form action="/notifications/{{ $notification->id }}/edit" method="POST" name="updateNotificationForm" class="update-notification-form">
@csrf
{{-- @method('PUT') --}}
<input type="hidden" name="id" value="{{ $notification->id }}">
<p class="update-notification pl10">Mark read</p>
</form>
<form action="/notifications/delete/{{ $notification->id }}" method="POST" class="delete-notification-form">
@csrf
<input type="hidden" name="id" value="{{ $notification->id }}">
<p class="delete-notification pl10">Delete</p>
</form>
</div>
这是Javascript:
方法一:
document.querySelectorAll('.update-notification').forEach(item => {
item.addEventListener('click', event => {
console.log("Mark read clicked");
// submit form
});
});
方法二:
document.addEventListener('click', function (event) {
if ( event.target.classList.contains('update-notification') ) {
console.log("Mark read was clicked");
// submit form
}
}, false);
显示console.log
每个方法都链接到数组中的每个元素,但我不知道如何提交表单。
我很感激任何帮助!
解决方案
解决方案是简单地定位目标本身的父节点并触发提交。
document.querySelectorAll('.update-notification').forEach(item => {
item.addEventListener('click', event => {
console.log("Mark read clicked");
event.target.parentNode.submit();
});
});
推荐阅读
- c# - 小写 Json 导致 ASP.NET MVC 5
- c - free() 函数和从“指向非 void 数据类型的指针”到指向 void 数据类型的指针的隐式类型转换
- c# - 从 WM_DEVICECHANGE LParam 获取设备的友好名称
- python-3.x - “PySide2.QtGui”没有属性“QRegularExpressionValidator”
- python - 使用 FuncAnimation 绘制带有彩色方块的网格的最佳方法
- go - Golang 中带有带外预共享密钥 (PSK) 的 TLS
- vb.net - Timer.tick 在 1 分钟内来回
- c# - 如何通过单击复选框更改标签文本(数字)?
- google-api - 调用 Google Admin Directory API 编写恢复电子邮件时,我收到响应状态代码 400 BAD REQUEST
- r - R echarts4r - 轴格式日期