[英]Get id from td of a table
<script type="text/javascript">
function LoadData(){
var url = serverURL+"/List.php";
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(data){
$.each(data.data, function (key, value) {
var doc_id=value['id'];
var doc_name=value['name'];
var doc_speci = value['specialize'];
$("#myTable").append("<tr><td>"+doc_name+"</td><td>"+doc_speci+"</td><td class='retrieve' data-did="+doc_id+" style='cursor: pointer;'>EDIT</td></tr>");
});
},
error: function(data){
toastr.error("Opps! Something went wrong");
$(".se-pre-con").fadeOut("slow");
},
});
}
</script>
The above appends a tr to my html table below. 以上将tr添加到下面的html表中。 The HTML TABLE is as follows:
HTML TABLE如下:
<table id="myTable" class='table table-bordered table-hover table-striped'>
<tr>
<th>Name</th>
<th>Specialization</th>
<th>Action</th>
</tr>
</table>
Now i want to retrieve the id from the data attribute from td class retrieve so that i can send the id and redirect it to other page for editing. 现在我想从td类检索数据属性中检索id,这样我就可以发送id并将其重定向到其他页面进行编辑。
First, to add your data attribute you should make sure you add quotes around the value: 首先,要添加数据属性,应确保在值周围添加引号:
data-did='"+doc_id+"'...
So the rendered cell must look something like this: 因此,渲染单元必须是这个样子:
<td class='retrieve' data-did='n' style='cursor: pointer;'>EDIT</td>
(where n is some value) (其中n是某个值)
Then you can easily retrieve this value with jQuery: 然后,您可以使用jQuery轻松检索此值:
$('specific-td').data('did'); //specific-td referes to a specific cell in a row, you must write that, this is just an example
To get all of the rows: 获取所有行:
var ids = [];
$('.retrieve').each(function() {
ids.push($(this).data('did'));
});
Example: If you have a button for example: 示例:如果您有一个按钮,例如:
$('#myTable').on('click', '.retrieve input[type="button"]', function() {
var id = $(this).parent().data('did');
alert(id);
});
JSFiddle : https://jsfiddle.net/y2an0fu7/1/ JSFiddle : https : //jsfiddle.net/y2an0fu7/1/
// Clicks the edit field
$("td.retrieve").on("click", function(e) {
var id = $(e.currentTarget).attr("data-did");
// do with the ID what you want
alert(id);
});
I'm aware that jQuery has a "data(...)" function but I've run into issues with that sometimes in the past. 我知道jQuery有一个“数据(...)”功能,但我有时会遇到问题。 "attr(...)" will do something similar but relies specifically on the attribute instead of stored objects.
“attr(...)”将执行类似的操作,但特别依赖于属性而不是存储的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.