javascript - 获取从 ajax 调用动态添加的特定输入的值
问题描述
我想获取onclick
事件中特定输入的值
这个函数从我的后端检索所有数据
Javascript
function getProjects() {
$.ajax({
method: 'GET',
dataType: 'json',
data: {
functionToCall: 'project',
},
url: 'http://localhost/WBS/php/api/requests/get.php',
success: (response) => {
$.each(response, function () {
$.each(this, function (index, value) {
$('#project-body').append(
`
<tr>
<td>
<input class="form-control projectid" type="hidden" name="projectid[]" value="${value.projectid}">
</td>
<td>
<input class="form-control projectName" type="text" name="projectName[]" value="${value.title}">
</td>
<td>
<input class="form-control description" type="text" name="description[]" value="${value.description}">
</td>
<td>
<input class="form-control estimatedTime" type="text" name="estimatedTime[]" value="${value.Estimated_time}">
</td>
<td>
<input class="form-control actualTime" type="text" name="actualTime[]" value="${value.Actual_time}">
</td>
<td>
<a class="btn btn-info addTask" href="Overview.html?id=${value.projectid}" role="button">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Add task
</a>
</td>
<td>
<button value="${value.projectid}" type="button" name="deleteProject" class="btn btn-danger deleteProject">
<i class="fa fa-angle-right" aria-hidden="true"> </i> Delete project
</button>
</td>
</tr>
`
);
});
});
},
error: () => {
console.error('Something went wrong with the getProjects function');
},
});
}
我想得到这个特定输入的值
<td>
<input class="form-control projectid" type="hidden" name="projectid[]" value="${value.projectid}">
</td>
我试过用这个
$(document).on('click', '.btn.btn-danger.deleteProject', () => {
let id = $(this).find('tr').closest('.form-control.projectid');
deleteProject(id); // this is an ajax call that deletes a project with said ID
});
但是console.logging这在所有按钮点击上都返回未定义,我尝试对其进行硬编码
$(document).on('click', '.btn.btn-danger.deleteProject', () => {
let id = $('.btn.btn-danger.deleteProject').val();
deleteProject(id);
});
这会返回一个 ID,问题是它始终只返回第一个 ID。
我的问题是,如何从 onclick 事件中获取所述输入值?
解决方案
closest
测试元素本身及其ancestors
匹配选择器。
你需要做的是:找到最接近tr
点击的按钮,然后在里面tr
找到输入,所以是这样的:
$(document).on('click', '.btn.btn-danger.deleteProject', function() {
const id = $(this).closest('tr').find('.form-control.projectid').val();
deleteProject(id);
});
推荐阅读
- android - 隐藏菜单项时如何从导航抽屉中删除隐藏的项目空间?
- oracle-apex - Oracle Apex 中的计算有问题?
- d3.js - 为 D3 圆弧内半径设置边框
- ssh - 使用 Remmina 打开 SSH 隧道以进行 VNC 连接时卡住
- coldfusion - 在包含 HTML 标签的表达式中使用 ColdFusion 中的 Evaluate 函数
- json - 你如何让 json 中的列表指向相同的值?
- html - 如何处理 aria-label 中的空格?
- c# - 如何在 C# 中从 SQL Server 数据库填充数据网格视图
- sql-server - 非聚集索引 - 几乎相同需求的一个或两个索引(两个表之间的连接)?
- c# - 我如何计算每个中具有不同代码的票