如何使用纯JavaScript或打字稿访问表的最后一列

问题描述 投票:0回答:2

[试图在纯JavaScript中访问每行的最后一列,但不在jquery中,但不起作用。任何人都知道,请帮忙找到解决方案。

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

javascript typescript angular7 angular8
2个回答
1
投票

我不确定为什么在使用angular时为什么要以纯JavaScript方式使用它,

无论如何,我可以使用dom querySelector() methods ..以纯JavaScript的方式为您提供解决方案。

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');
    lastColumn.addEventListener('change', this.getEvent.bind(this, select))
  }

}

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

我提出了一种解决方案,可以在选择的每一行的最后检索每个选择框的值。

Forked Stackblitz here ...


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.