如何在纯 javascript 或打字稿中访问 table 的最后一列

How to access table's last column in pure javascript or typescript

试图访问纯 javascript 而非 jquery 而非 working.Anyone 中每一行的最后一列知道请帮助找到解决方案。

app.component.html:

<div id="contentId">
<table>
  <thead>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </thead>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td><select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select></td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td><select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select></td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td><select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select></td>
  </tr> 
</table>
</div>

演示:https://stackblitz.com/edit/amexio-breadcrumb-demo-jyxytf?file=src/app/app.component.ts

我不确定为什么在使用 angular、

时要以纯粹的 javascript 方式使用它

无论如何,我能够以 javascript 的方式为您提供解决方案 dom querySelector() methods ..

ngOnInit(){

  const gettable = document.getElementById("contentId").querySelector('table');
  const rows = gettable.getElementsByTagName('tr');

  for (let i=0; i<rows.length; i++)
  {
    const columns = rows[i].getElementsByTagName("td");
    const lastColumn = columns[columns.length - 1];
    const select = lastColumn.querySelector('select');
    select.addEventListener('change', this.getEvent.bind(this, select))
  }

}

getEvent(selectedItem){  
  console.log(selectedItem.value);
  return event;
}

我已经制定了一个解决方案来检索 selection 上每一行最后的每个 select 框值..

Forked Stackblitz here ...

更新:

如果您正在使用 primeng table 并且您需要从 table (p-table) 中检索值,您可以使用 angular elementRef 并使用

获取值
const table = this.elementRef.nativeElement.querySelectorAll('p-table table');

并且 table 将在 ngAfterviewInit 生命周期挂钩中完全初始化,因此从 ngOnInit() 挂钩更改。

还添加了 ChangeDetectionStrategy 以检测 select 框值的变化..

使用 primeng 更新了 stackblitz:https://stackblitz.com/edit/primeng-tables-ubgkcm

假设您要在每行的最后一个 td 元素中包含的 select 元素上安装事件 change 侦听器,您可以执行以下操作:

ngOnInit(){ 
    const table: HTMLTableElement = document.getElementById("contentId").querySelector('table');
    Array.from(table.getElementsByTagName('tr')).map(tr => tr.querySelector('td:last-of-type').querySelector('select').addEventListener('change', event => this.getEvent(event)));
}

请看一下分叉的StackBlitz