从动态创建的表获取ID

时间:2018-06-28 17:27:57

标签: javascript jquery html

我是JS的新手,目前正在尝试获取<th> id作为<td>的一部分,并尝试获取动态创建的表的id。

<table id='table'>
          <thead>
            <tr>
              <th>Student</th>
              <th id='Lesson_1'>Lesson 1</th>
              <th id='Lesson_2'>Lesson 2</th>
              <th id='Lesson_3'>Lesson 3</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>Jhon Doe</td>
              <td><input type='checkbox' id='check1' onclick="checkIn(this.id);"> </td>
              <td><input type='checkbox' id='check2' onclick="checkIn(this.id);"> </td>
              <td><input type='checkbox' id='check3' onclick="checkIn(this.id);"> </td>
          </tbody>
        </table>
<script>
function checkIn(checkBoxId){
          var checkBox = document.getElementById(checkBoxId);
          var LessonID_checkBox = $('#table thead tr').find('th[id]').attr(id);
          console.log(LessonID_checkBox);
</script>

UPD: _预期的输出:Lesson_1check1 _

Lesson列的数量取决于数据库中的课程数量。我正在做的是玩这段代码$('#table thead tr').find('th').attr(id);,但是似乎不明白该怎么做。

Added picture for clarity

3 个答案:

答案 0 :(得分:1)

您应该能够使用如下属性进行相同的操作:

$("th[id]");

如果要获取具有特定ID的,可以使用以下方法:

  $("th[id='I_WANT_THAT_ID']");

答案 1 :(得分:1)

不确定是否要获取一个特定的th id或任何第th个元素的id。如果要全部获取,则需要选择第th个元素,然后循环遍历以获取每个id。像这样:

["12121","434536"]

答案 2 :(得分:0)

您可以遍历tds内的tbody并从thead获取相关的td。然后获取id并将其附加

$("#table tbody tr td").each(function(i, v) {
  let getIdFromTH = ($("#table thead tr th").eq(i).attr('id'))
  let currID = $(v).find('input').attr('id');
  let newId = getIdFromTH + "-Test "
  $(v).find('input').attr('id', newId)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table'>
  <thead>
    <tr>
      <th>Student</th>
      <th id='I_WANT_THAT_ID'>Lesson</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Jhon Doe</td>
      <td><input type='checkbox' id='BE_HERE+something'> attandance </td>
  </tbody>
</table>