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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:34:23  来源:igfitidea点击:

Get the text of nth TD with all tr having particular class

jqueryjquery-ui

提问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

Try this

尝试这个

$('tr.warning').each(function(){  
    alert($(this).find('td').eq(1).text());
    });

Demo Here

演示在这里

回答by Dipesh Parmar

Try

尝试

$('tr.warning td:eq(1)').text();

if you want more specific answer than use :nth-childselector

如果您想要比使用:nth-child选择器更具体的答案

$('tr.warning td:nth-child(2)').text()

http://jsfiddle.net/dbuZG/5/

http://jsfiddle.net/dbuZG/5/

回答by chucknelson

Using jQuery's :nth-childselector 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 :eqapplies 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>容器的位置,因此只返回一个元素)。