如何使用 JQuery 获取 HTML 表格中单元格的值

8

我看到很多帖子都谈论了我的问题,但没有一个对我有效。

我有一个HTML表格,我想获取单元格(th)“Index”下的值。我该如何使用jQuery实现:

<table id="htmlTable">
    <caption>Informations des hotspots</caption>
    <thead>
        <tr>
            <th>Index</th>
            <th>Nom du hotspot</th>
            <th>Image du hotspot</th>
        </tr>
    </thead>
    <tbody>
        <tr id="0">
            <td>0</td>
            <td>Hotspot Fribourg Centre</td>
            <td>../images/logos_hotspot/logo_wifi_centre.png</td>
            <td>
                <input type="button" value="supprimer" />
            </td>
        </tr>
        <tr id="1">
            <td>1</td>
            <td>Hotspot Avry Centre</td>
            <td>../images/logos_hotspot/logo_wifi_avry.png</td>
            <td>
                <input type="button" value="supprimer" />
            </td>
        </tr>
    </tbody>
</table>
6个回答

13

我想这会对你有所帮助。

var MyRows = $('table#htmlTable').find('tbody').find('tr');
for (var i = 0; i < MyRows.length; i++) {
var MyIndexValue = $(MyRows[i]).find('td:eq(0)').html();
}

2

通过这个相对的td值来实现

 var tharr=[];
    $("#htmlTable").find("tbody tr").each(function(){
    tharr.push($(this).find("td:eq(0)").text());

    });

alert(tharr.join(",")); //by this you get 0,1

如果你只想要值,可以这样做。
$('#htmlTable tr th:first').text();

2

试试这个:

var text = $('#htmlTable tr th:first').text(); // = "Index"

Example fiddle


谢谢你的回答。它很好地工作了,但我想要在索引单元格下方显示值。 - loi219

2
为了获取<th>标签本身的内容:
$('#htmlTable th:first').html()

遍历后续的<td>标签并获取它们的值:
$('#htmlTable tr:gt(0)').each(function(){
    console.log($('td:first', $(this)).html());
});

或者你可以自己尝试操作:http://jsfiddle.net/chaiml/p2uNv/4/


1

尝试以下代码。

$(document).on("click", "[id*=tableId] tr", function () {

   var a = $(this).find("td").eq(3).children().html(); 

   alert(a);
});

1
 let s_=jqueryDTtable.column(m).nodes()[n].textContent

其中m是从0开始的行中的列号,n是您的节点的顺序号,范围从0到列节点数-1。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接