0
我從一個API使用jQuery用下面的代碼如何從td元素中選擇特定的ID?
type: 'GET',
dataType: 'json',
url: "http://api.football-data.org/v1/competitions/426/teams",
processData: true,
success: function (data, status) {
var trHTML = '';
$.each(data.teams, function (key, item) {
var id = item._links.self.href;
var indexOfLastBackSlash = id.lastIndexOf("/") + 1;
id = id.substring(indexOfLastBackSlash);
//$('<option>', { text: item.TeamName, id: item.ID }).appendTo('#lstTeams');
var $row = $("<tr>", { class: "info" });
$row.append($("<td>").html(item.name));
$row.append($("<td>").html(item.code));
$row.append($("<td>").html(item.shortName));
$row.append($("<td>").html(item.squadMarketValue));
$row.append($("<td>").html(item.crestURL));
$row.append($("<td>").html(id));
$row.appendTo($('#teamsTable'));
我想通過點擊一個TD元素上選中一行並獲得ID,並將其放置在一個URL中提取數據。我試過這個
$("#teamsTable").on('click', 'td', (function() {
//var id = $(this).attr("id");
//location.reload();
$.ajax({
type: 'GET',
dataType: 'jsonp',
crossDomain: true,
url: "http://api.football-data.org/v1/teams/" + id + "/fixtures",
但它似乎從表中選擇所有ID。任何建議如何只抓住一個ID?
'$(this).closest('tr')'將得到最接近的行。 '.parent()'也適用於這裏。我喜歡'.closest()',因爲它更通用。它基本上開始向上搜索(在DOM樹上),直到找到一個「tr」。與之相反的是'.find(...)',它向下搜索(嵌入到嵌套對象中)。 – nurdyguy
在您的API調用部分中,它看起來不像您爲TR或TD分配任何ID。如果它適用於整行,我會建議把ID放在TR上。 (類似'$ row.prop('id',id);') – James