简体   繁体   English

访问表格单元格中div的内容

[英]Access contents of div inside table cell

I have a JSFiddle here . 我在这里有一个JSFiddle

I am trying to access the text content of the div with class '.item_description' for all rows in a table where a checkbox has been checked, but I cannot seem to get it.The checkbox is in a nested table in each row. 我正在尝试使用类别为.item_description的div的文本内容访问已选中复选框的表中的所有行,但似乎无法获取该复选框。该复选框位于每行的嵌套表中。

My HTML is: 我的HTML是:

<table id="table-tasks-list" class="table-hover">
  <tbody>
    <tr id="row-task-10572" class="task-modal-row">
      <td >
        <div class="task_description pull-left" style="padding:5px 0 0 5px;">Qui at dolore sit alias cum voluptate ad...</div>
        <table class="pull-right" style="border:none;">
          <tbody>
            <tr>
              <td style="width:80px;border:none;">2015-02-23</td>
              <td class="hours" style="width:30px;border: none;">8.00</td>
              <td class="row-icon tasks-check-box" style="border: none;">
                <label class="checkbox-hold">
                  <input type="checkbox" name="bill-task" id="chk-10572" class="task-checkbox ion-fw" checked=""><span class="fake-input checkbox-icon ion-android-checkbox-outline-blank ion-fw" data-chk-id="10572"></span></label>
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
    <tr id="row-task-10573" class="task-modal-row">
    ....

In my JS, I do: 在我的JS中,我这样做:

$('table#table-tasks-list tbody tr td input.task-checkbox').each(function(i, check) {       
  if ($(check).is(':checked')) {
    console.log($(check).closest('table#table-tasks-list tbody tr').find('.task_description').text());
 }     
});

But i get empty results. 但是我得到的结果是空的。 What have i missed? 我错过了什么? Thanks! 谢谢!

Use 采用

$(check).closest(".task-modal-row").find(".task_description").text();

To access the content of the closest .task_description 访问最接近的.task_description的内容

According to your code it should be like this: 根据您的代码,它应该是这样的:

$(check).closest('.task-modal-row').find('.task_description').text()

Demo : https://jsfiddle.net/TheRealPapa/sw5Lh6pa/1/ 演示: https : //jsfiddle.net/TheRealPapa/sw5Lh6pa/1/

Your closest() targets the whole table and outputs the contents of all .task-description it finds, regardless of checkboxes. closest()以整个表为目标,并输出找到的所有.task-description的内容,而不管复选框如何。 You only need to go up to the containing tr : 您只需要转到包含tr

console.log($(check).closest('tr[id^="row-task-"]').find('.task_description').text());

I don't have an answer about why it doesn't work. 我没有答案,为什么它不起作用。 However, I believe I reached similar problem and fixed it by using $(this) inside the loop instead of using the second argument of the callback function ( check in your example). 但是,我相信我也遇到了类似的问题,并通过在循环内使用$(this)而不是使用回调函数的第二个参数(在您的示例中check )来解决此问题。 I hope this helps... 我希望这有帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM