1

When someone clicks on the Download button in my table, I want to pass the date values from that particular row to a function. Currently I can only pass the date values from the first table row.

This is the selector I'm using:

$(this).parent().find('#period-start');

Which always returns:

[<td id=​"period-start">​5/1/2013​&lt;/td>]

I've tried combinations of the parent, child, find and closest selectors, but haven't been able to stumble across the correct one to grab the date values from the current row. Thanks.

Table

<table id="tblStatements" class="table">
            <thead>
                <tr>
                    <th>Period Starting</th>
                    <th>Period Ending</th>
                    <th>Download</th>
                </tr>
            </thead>
            <tbody>

<tr>
  <td id='period-start'>5/1/2013</td>
  <td id='period-end'>5/31/2013</td>
  <td><button type='submit'>Download</button></td>
</tr>

<tr>
  <td id='period-start'>4/1/2013</td>
  <td id='period-end'>4/30/2013</td>
  <td><button type='submit'>Download</button></td>
</tr>

<tr>
  <td id='period-start'>3/1/2013</td>
  <td id='period-end'>3/31/2013</td>
  <td><button type='submit'>Download</button></td>
</tr>

</tbody>
</table>
4

5 回答 5

7

ID在 HTML中总是应该是唯一的。所以,你可以试试这个,不使用 ID:

// Get the first td
var periodStart = $(this).closest('tr').children('td:eq(0)').text();  

// Get the second td
var periodEnd = $(this).closest('tr').children('td:eq(1)').text();  

小提琴演示

于 2013-06-26T09:37:56.303 回答
2

使用这个 -不要使用重复的 ID,而是使用类

$(this).closest('tr').find('#period-start');

或者 -

$(this).closest('td').siblings('#period-start');
于 2013-06-26T09:29:29.733 回答
1

尝试这个

 $(this).parent().siblings('#period-start');

确保您的所有 id 都是唯一的..您的 HTML 无效..将其更改为 class 并尝试此操作

  $(this).parent().siblings('.period-start');
于 2013-06-26T09:31:30.877 回答
1

您不应使用多个具有相同 id 的元素使用类 insidead。

<tr>
  <td class='period-start'>5/1/2013</td>
  <td class='period-end'>5/31/2013</td>
  <td><button type='submit'>Download</button></td>
</tr>

<tr>
  <td class='period-start'>4/1/2013</td>
  <td class='period-end'>4/30/2013</td>
  <td><button type='submit'>Download</button></td>
</tr>

<tr>
  <td class='period-start'>3/1/2013</td>
  <td class='period-end'>3/31/2013</td>
  <td><button type='submit'>Download</button></td>
</tr>

并使用此代码选择适当的元素

$(this).parents('tr').find('.period-start');
于 2013-06-26T09:32:20.297 回答
0

尝试这个

$.trim($(this).closest('tr').find('[id="period-start"]').html());//this gives start date
于 2013-06-26T09:35:12.213 回答