我正在使用 jQuery 将 API 调用中的数据附加到表中。 我现在想做的是,如果有人单击表中的一行,我想将该行的 id 传递到另一个屏幕(编辑屏幕)以编辑该行的详细信息。 当我尝试向该行添加单击功能时,尽管它会中断,因为表中未填充数据。 我尝试过什么
选项1
$.get(...){
$.each(res.data, function (index, value) {
$(".TData").append('"<tr id="'+value.id'"><td>'+value.description+'</td> <td>'+value.order+' </td> </tr>"')
})
}
$(".TData tr").click(function(event){
console.log(event.id); <- doesn't return value.id
(in reality this will redirect to the next page passing the id)
})
以及 onclick 的行内赋值
$.get(...){
$.each(res.data, function (index, value) {
$(".TData").append('"<tr onclick="rowClick(e)" id="'+value.id'"><td>'+value.description+'</td> <td>'+value.order+' </td> </tr>"')
})
}
function rowClick...
这两种方法都不起作用,因为表中没有填充选项 2。 在选项 1 下,id 永远不会被插入控制台来执行任何操作。有人可以解释我做错了什么吗? }
最佳答案
- 修复字符串
'"
或者使用模板文字 - 使用 JS
Array.prototype.map()
创建行数组 - 使用 jQuery 的对象表示法元素选项
- 在填充所有
$rows
数组后仅追加一次(以获得更好的性能) - 使用
.on()
方法为每行分配点击监听器(请参见下面的示例)
const res = { // Just to fake the response
"data": [
{"id": 111, "description": "Lorem", "order": "Order 1"},
{"id": 222, "description": "Ipsum", "order": "Order 2"}
]
};
const $rows = res.data.map(obj => $('<tr>', {
id: obj.id,
append: `<td>${obj.description}</td><td>${obj.order}</td>`,
on: {
click() {
console.log(obj.id);
// You can also use $(this) to reference the clicked row
}
}
}));
// Append only once:
$(".TData").append($rows);
<table>
<thead>
<tr><th>Description</th><th>Order</th></tr>
</thead>
<tbody class="TData"></tbody>
</table>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
MDN - Template literals
MDN - Array map
jQuery API - jQuery
jQuery API - .on()
关于Jquery Append On click函数表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58174028/