【发布时间】:2021-09-01 20:39:30
【问题描述】:
我正在尝试对选定的动态元素进行 onclick 删除,但由于某种原因,它每次只选择第一个元素。
// Function to delete entries
$("#timesheet").on('click', '.delRow', function () {
const firstUrl = "API LINK..."
const secondUrl = document.getElementById("timesheetDetailsID").innerText
console.log(secondUrl)
const settings = {
"async": true,
"crossDomain": true,
"url": JSON.stringify(firstUrl + secondUrl),
"method": "DELETE",
"headers": {
"Content-Type": "application/json"
},
"processData": false,
success: function () {
alert("Yay")
},
error: function () {
//error handler
alert("Boo")
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
});
HTML 页面示例: Example of the HTML
//Dynamic HTML
const htmlTemplate = `
<tr id = "testDeleteTimesheet">
<td>${entry.hours}</td>
<td id = "timesheetDetailsID" style = "display: none;">${entry.timesheetDetailsId}</td>
<td>${chartDate}</td>
<td>${entry.contractCode}</td>
<td>${entry.activityCode}</td>
<td>${entry.otFlag}</td>
<td>${entry.notes}</td>
<td><button id=\"edit-" + counter + "\" class=\"btn editRow btnStyle btn-primary btn-sm\"><span class=\ "bi bi-pencil\"></span></button>
<button id=\"delete-" + counter + "\" class=\"btn delRow btnStyle btn-danger btn-sm\"><span class=\"bi bi-eraser\"></span></button></td>
</tr>
`;
这是我的静态 html 动态内容的目标
//.html page
<table class="table" id="timesheet">
<thead>
<tr>
<th scope="col">Hours</th>
<th scope="col">Date</th>
<th scope="col">ContractCode</th>
<th scope="col">Activity Code</th>
<th scope="col">OT</th>
<th scope="col">Notes</th>
<th scope="col" id="rowBtns"></th>
</tr>
</thead>
<tbody id="tsdata"></tbody>
</table>
【问题讨论】:
-
“只选择第一个元素”具体是什么意思?你的 HTML 是什么,特别是这段代码中的什么操作产生了意想不到的结果?
-
您需要共享 HTML 以获得更好的答案。但我相信您正在选择具有重复 id 值的组件。你应该按类名选择,看看它是否适合你。
-
您正在调用
$("#timesheet"),这是带有id="timesheet"的元素。一个 id 只需要分配给一个元素。因此,如果您有多个具有相同 ID 的元素,jQuery 只会带回它找到的第一个元素。 -
@Steve timesheet 位于 .html 文件中,该文件是所有动态
的包装器 @Zurez 抱歉,我刚刚用我的 html 更新了问题。
标签: javascript html jquery ajax