[英]Get value of Table Row with mouse click? (JQuery)
I have a table, where I display some data.我有一个表格,我在其中显示一些数据。 Every table row has a ID.
每个表行都有一个 ID。 This ID is the value of every tr-tag.
此 ID 是每个 tr-tag 的值。 When I click a row of the table, I want to display the ID in the console.
当我单击表格的一行时,我想在控制台中显示 ID。
Table:桌子:
$.getJSON(`http://localhost:5000/Flights/Flights/${fromAirport}/${toAirport}`)
.then(data => {
console.log(data);
$('#flights').find("tr:gt(0)").fadeOut().empty();
for (let item of data) {
console.log('entered loop');
$(`<tr value="${item.flightId}">`).appendTo('#flights')
.append($('<td>').html(item.date))
.append($('<td>').html(item.departureTime))
.append($('<td>').html(item.arrivalTime))
.append($('<td>').html(item.flightNr))
.append($('<td>').html(item.price))
.append($('<td>').html(item.airplane))
.append($('<td>').html(item.nrSeats))
.append($('<td>').html(item.nrVacant))
.append($('<td>').html(item.nrBooked))
.append($('<td>').html(item.flightId))
}
});
On Click Method:点击方法:
$('#flights').on('click', function (e) {
const entry = $(e.target.val());
console.log(entry);
});
This on click event is not working, but I do not really know why.这个点击事件不起作用,但我真的不知道为什么。 Maybe someone has a idea:)
也许有人有一个想法:)
Do you mean this?你是这个意思吗?
When the user clicks on a tr, it receives the value当用户点击一个 tr 时,它会收到该值
$('tr').on('click',function(){
value = $(this).attr('value');
console.log(value);
})
There are a couple of errors here:这里有几个错误:
tr
.tr
。 A syntax error: .val()
is a jQuery function, you can't use it on the target
, you have to close the parens before: $(e.target).val()
.语法错误:
.val()
is a jQuery function,你不能在target
上使用它,你必须在之前关闭括号: $(e.target).val()
。
Even then .val()
is used for inputs
, for this you have to access the attribute directly.即使那样
.val()
用于inputs
,为此您必须直接访问该属性。
All together, using event delegation , you can do the following:总之,使用事件委托,您可以执行以下操作:
$('#flights').on('click', 'tr', function() { console.log($(this).attr('value')); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="flights"> <tr value="1"> <td>Item1</td> </tr> <tr value="2"> <td>Item1</td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.