jQuery 获取所有 tr 具有特定类的第 n 个 TD 的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18416408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the text of nth TD with all tr having particular class
提问by jerin
The code which i am working on is as follows:
我正在处理的代码如下:
<table>
<tr class="warning">
<td> 1 </td>
<td> name </td>
<td> address </td>
<td> phone no </td>
<td> Location </td>
</tr>
<tr>
<td> 3 </td>
<td> name2 </td>
<td> address2 </td>
<td> phone no2 </td>
<td> Location2 </td>
</tr>
<tr class="warning">
<td> 6 </td>
<td> name5 </td>
<td> address5 </td>
<td> phone no5 </td>
<td> Location5 </td>
</tr>
<tr>
<td> 7 </td>
<td> name6 </td>
<td> address6 </td>
<td> phone no6 </td>
<td> Location6 </td>
</tr>
I like to get the text of all second TD with all tr with class warning.
我喜欢获取所有带有类警告的所有 tr 的所有第二个 TD 的文本。
I have tried using _.each method but wasn't succesful
我曾尝试使用 _.each 方法但没有成功
回答by S. S. Rawat
回答by Dipesh Parmar
Try
尝试
$('tr.warning td:eq(1)').text();
if you want more specific answer than use :nth-child
selector
如果您想要比使用:nth-child
选择器更具体的答案
$('tr.warning td:nth-child(2)').text()
回答by chucknelson
Using jQuery's :nth-child
selector along with .each()
should work for you.
使用 jQuery 的:nth-child
选择器 with.each()
应该对你有用。
Fiddle: http://jsfiddle.net/chucknelson/KDy8X/
小提琴:http: //jsfiddle.net/chucknelson/KDy8X/
Jquery
查询
$(function() {
//use the :nth-child selector to get second element
//iterate with .each()
$('table tr.warning td:nth-child(2)').each(function(index, element) {
var name = $(element).html();
$('#name-list').append('<li>' + name + '</li>');
});
});
Some additional HTML:
一些额外的 HTML:
<div id="warning-names">
Warning Names:
<ul id="name-list">
</ul>
</div>
回答by Alnitak
This will obtain the list of names in an array:
这将获得数组中的名称列表:
var names = $('tr.warning td:nth-child(2)').map(function() {
return $(this).text();
}).get();
demo at http://jsfiddle.net/alnitak/CjQAh/
演示在http://jsfiddle.net/alnitak/CjQAh/
(using :eq(1)
doesn't work, because the :eq
applies to the index within the entire set of returned elements, not the element's position relative to its <tr>
container, and so only returns one element).
(使用:eq(1)
不起作用,因为:eq
应用于整个返回元素集中的索引,而不是元素相对于其<tr>
容器的位置,因此只返回一个元素)。