Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript从特定表中获取特定行?_Javascript_Html_Css Tables - Fatal编程技术网

使用JavaScript从特定表中获取特定行?

使用JavaScript从特定表中获取特定行?,javascript,html,css-tables,Javascript,Html,Css Tables,假设我的动态HTML如下所示: <table id="DanishCompanies"> <tr><th>Name</th><th>Employees</th><th>Founded</th></tr> <tr id="19"><td>Company A</td><td>80</td>

假设我的动态HTML如下所示:

<table id="DanishCompanies">
  <tr><th>Name</th><th>Employees</th><th>Founded</th></tr>
  <tr id="19"><td>Company A</td><td>80</td><td>1980</td></tr>
  <tr id="17"><td>Company B</td><td>12</td><td>1910</td></tr>
  <tr id="26"><td>Company C</td><td>5000</td><td>2015</td></tr>
</table>
<table id="SwedishCompanies">
  <tr><th>Name</th><th>Employees</th><th>Founded</th></tr>
  <tr id="10"><td>Company D</td><td>500</td><td>1950</td></tr>
  <tr id="12"><td>Company E</td><td>900</td><td>1990</td></tr>
  <tr id="17"><td>Company F</td><td>90</td><td>2010</td></tr>
</table>
<table id="NorwegianCompanies">
  <tr><th>Name</th><th>Employees</th><th>Founded</th></tr>
  <tr id="17"><td>Company G</td><td>105</td><td>1970</td></tr>
  <tr id="18"><td>Company H</td><td>100</td><td>1980</td></tr>
  <tr id="19"><td>Company I</td><td>45</td><td>2000</td></tr>
</table>

我不能只使用getElementById来获取id 17,因为这些表的顺序是随机的,我会冒着获得丹麦或挪威公司的风险。

您只是没有使用正确的选择器

#DanishCompanies tr[id="17"]
将为您提供id为17的tr,这是Danish公司的孩子:

const row=document.querySelector'danishcompanys tr[id=17]; const year=row.cells[2].innerHTML; 对数年; 名称 员工 成立 A公司 80 1980 B公司 12 1910 C公司 5000 2015 名称 员工 成立 D公司 500 1950 E公司 900 1990 F公司 90 2010 名称 员工 成立 G公司 105 1970 H公司 100 1980 第一公司 45 2000
这种带有数字值的id方式使css选择语法复杂化

函数getTDval tableId、rowId、colNum { 返回文件 .querySelector`table${tableId}tr[id=${rowId}]` .cells[colNum].textContent } console.log getdval'swedishcompanys',17',2 员工姓名基金 A801980公司 B121910公司 公司C50002015 员工姓名基金 D5001950公司 E9001990公司 F902010公司 员工姓名基金 G1051970公司 H1001980公司 I452000公司 如果您不能依赖getElmentById,这意味着您做错了什么,那么id在整个html中应该是唯一的。我建议使用一种新的命名技术,您可以将父表id与当前行id连接起来。例如:

员工姓名基金 G1051970公司 H1001980公司 I452000公司 这样你就可以打电话了

const row=document.getElementByIdrowId
在页面中重复使用相同的id值是无效的HTML。您可以使用私有数据-。。。属性

除此之外,下面一行获取本例中第三个子节点第三列的可读文本,即字符串形式的年份

document.querySelector('#DanishCompanies tr[id="17"]')
    .children[2].innerText;

您是否以任何方式控制此HTML?技术上不允许多个元素共享同一id,尽管我所知道的每个浏览器和元素选择器都允许使用它,并且通常使用它做正确的事情,拥有全局唯一的id也可以解决您的问题。
document.querySelector('#DanishCompanies tr[id="17"]')
    .children[2].innerText;