如何使用javascript在动态表格的点击列表中获取值

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

“

您可以在这张图片中看到,我有表格。现在,如果我单击下表中的任何一个表名,如“反馈”,则如何获取它们的值。表是动态的。下面是显示表名的代码。

<table class="table  table-hover" style="margin-top: 25px;width:300px;">
  <thead>
    {% for i in tables %}
    <tr>
      <th > {{ i }} </th>
    </tr>
      {% endfor %}
  </thead>
</table>

注意,i是表名的值。

我想在这里添加两件事:

  1. 点击监听器
  2. 使用JavaScript单击表获取值
javascript html flask onclicklistener dynamic-tables
1个回答
1
投票

要获得单击的元素,您可以侦听表上的单击事件,然后使用event.target属性获得被单击的元素。

// set up the 'click' event listener
myTable.addEventListener('click', event => {
  const clickedElement = event.target;

  // now that you have the clicked element, do what you want with it
  let stuffIWant = clickedElement.<some method or property of element>;
});

从问题的示例看来,您正在寻找<th>元素的内容。如果是这样,您可以使用:

stuffIWant = clickedElement.innerText;

一个工作示例:

// listen for all 'click' events within table
const tbl = document.getElementById('tbl');
tbl.addEventListener('click', event => {
  const el = event.target;
  alert(`you clicked "${el.innerText}"`);
});
#tbl {
  background-color: #aaa;
  margin: 12px;
}
th {
  padding: 0.5rem 2rem;
  border: 1px solid #999;
}
/* change cursor to hand on hover */
th:hover {
  cursor: pointer;
}
<table id="tbl">
  <thead>
    <tr><th>Feedback</th></tr>
    <tr><th>Complaint</th></tr>
    <tr><th>Praise</th></tr>
  </thead>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.