【问题标题】:Access contents of div inside table cell访问表格单元格内div的内容
【发布时间】:2017-01-29 09:55:02
【问题描述】:

I have a JSFiddle here.

我正在尝试使用“.item_description”类访问 div 的文本内容,以访问表中已选中复选框的所有行,但我似乎无法获取它。复选框位于每个嵌套表中行。

我的 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">
    ....

在我的 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());
 }     
});

但我得到空的结果。我错过了什么?谢谢!

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    使用

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

    访问最近的.task_description的内容

    【讨论】:

      【解决方案2】:

      根据你的代码应该是这样的:

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

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

      【讨论】:

        【解决方案3】:

        您的closest() 以整个表为目标,并输出它找到的所有.task-description 的内容,无论复选框如何。你只需要上到包含tr

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

        【讨论】:

        • 请注意,如果可能,最好使用id 选择器而不是类选择器,因为它们往往更快并且需要更少的资源。这就是为什么我更喜欢[id^="row-task-"] 而不是.task-modal-row。如果您没有很多行,这并不是那么重要,但是当您获得更多元素时,它可能会使页面感觉迟缓或停止动画。
        【解决方案4】:

        我不知道为什么它不起作用。但是,我相信我遇到了类似的问题并通过在循环中使用$(this) 而不是使用回调函数的第二个参数(在您的示例中为check)来修复它。我希望这会有所帮助...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-05-22
          • 1970-01-01
          • 2014-07-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-30
          相关资源
          最近更新 更多