我从设计师那里得到了以下代码:
<table class="items">
<thead>
<tr>
<th id="name">name</th>
<th id="category">category</th>
<th id="zip">zip</th>
<th id="city">city</th>
<th id="street">street</th>
<th id="latitude">latitude</th>
<th id="longitude">longitude</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MyCompany</td>
<td>Company</td>
<td>18360</td>
<td>Stroudsburg</td>
<td>4 Scott Str.</td>
<td>40.9891</td>
<td>-75.1962</td>
</tr>
</tbody>
</table>
使用jQuery,如何通过考虑具有指定
th
的id
元素来获取经度和纬度值?列的顺序以后可能会更改,因此不能选择直接索引。但是,id
值将保持不变。 最佳答案
您可以使用 .index()
method:
var latIndex = $("#latitude").index(),
longIndex = $("#longitude").index();
// do something with the values from each row
$("tbody tr").each(function() {
var $tds = $(this).find("td"),
latValue = $tds.eq(latIndex).text(),
longValue = $tds.eq(longIndex).text();
console.log(latValue + ", " + longValue);
});
演示:http://jsfiddle.net/mjaVp/
关于javascript - 如何获取特定元素的索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9728035/