【问题标题】:How to write click event for table's first column如何为表格的第一列编写点击事件
【发布时间】:2020-04-03 14:11:18
【问题描述】:

我正在尝试为表格的第一列编写点击事件。如果我单击第一列 ID,我想在警报框中获取该值。我试过了,但它不起作用。 Rows 没有采用 Angular 7 和 8。

不要使用像#tableId 这样的元素引用。请使用表ID。

app.component.html:

  <table id="tableId">
  <thead>
    <th>Id</th>
    <th>Contact</th>
    <th>Country</th>
  </thead>
  <tr>
    <td>12345</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>12346</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>12347</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>12348</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>12349</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>12310</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

app.component.ts:

 ngAfterViewInit() {
    const table = <HTMLTableElement> document.getElementById('tableId');
    for (let row of table.rows) {
      const firstCell = row.childNodes.item(0);
      firstCell.addEventListener('click', () => alert(firstCell.textContent));      
      (<HTMLElement> firstCell).setAttribute('style', 'cursor: pointer;');
    }
  }

【问题讨论】:

标签: javascript typescript angular7 angular8


【解决方案1】:

在 html 中为您的表 #tableId声明引用变量。

在组件内引用tableId变量

@ViewChild("tableId") table: ElementRef;

为所有第一个单元格附加点击事件

ngAfterViewInit(){
     let tblElement = this.table.nativeElement;
      for (let row of tblElement.rows) {
      const firstCell = row.childNodes.item(0);
      firstCell.addEventListener('click', () => alert(firstCell.textContent));      
      (<HTMLElement> firstCell).setAttribute('style', 'cursor: pointer;');
    }
  }

工作example

【讨论】:

    【解决方案2】:

    为 tr 添加 onclick 事件(这样如果用户点击表格中的任意位置,您将获得相应的行 ID)并获得子项。

    function test(event){
      console.log($(event).find('td').eq(0).text());
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="tableId">
      <thead>
        <th>Id</th>
        <th>Contact</th>
        <th>Country</th>
      </thead>
      <tr onclick = "test(this)">
        <td>12345</td>
        <td>Maria Anders</td>
        <td>Germany</td>
      </tr>
      <tr onclick = "test(this)">
        <td>12346</td>
        <td>Francisco Chang</td>
        <td>Mexico</td>
      </tr>
      <tr onclick = "test(this)">
        <td>12347</td>
        <td>Roland Mendel</td>
        <td>Austria</td>
      </tr>
    </table>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      相关资源
      最近更新 更多