如何在onclick函数中找到表头和行中的第一个元素?

时间:2013-01-28 23:05:56

标签: jquery html

我需要使用jquery在onclick函数中的行中找到表头和第一个元素,

$(document).ready(function(){
$(".items").delegate("tr", "dblclick", function(data){
    alert(data.target.innerHTML);
    alert($(this).find('td:eq(0)').html());

});
});

下面的代码给出了内部html和所选行中的第一个元素。我需要获取表头也与我单击的单元格相对应。

我已尝试将下面的代码放在dblclick函数中,但我认为传递的索引是错误的,我怎样才能获得正确的索引?

var headerValue= $(this).closest("table").find('th').eq($(this).index());
    alert(headerValue.text());

html table:

<table class="items">
<thead>
<tr>
<th id="sku-grid_c1">Name</th><th id="sku-grid_c2">Active</th><th id="sku-grid_c3">Date Created</th><th id="sku-grid_c4">Date Updated</th><th id="sku-grid_c5">Code</th><th id="sku-grid_c6">Price</th><th id="sku-grid_c7">Shipping</th><th id="sku-grid_c8">Max Qty</th><th class="button-column" id="sku-grid_c9">&nbsp;</th></tr>
</thead>
<tbody>
<tr class="odd">
<td>fbdh</td><td>yes</td><td>&nbsp;</td><td>&nbsp;</td><td>t67r6r7t6t</td><td>23</td><td>12</td><td>12</td></tr>
<tr class="even">
<td>bfhewfbuh</td><td>yes</td><td>&nbsp;</td><td>&nbsp;</td><td>678ty78tg</td><td>56</td><td>7</td><td>6</td></tr>
<tr class="odd">
<td>cdbj</td><td>no</td><td>&nbsp;</td><td>&nbsp;</td><td> hudhqu</td><td>12</td><td>12</td><td>1</td></tr>
<tr class="even">
<td>guyguyf</td><td>yes</td><td>&nbsp;</td><td>&nbsp;</td><td>678gy8t</td><td>56</td><td>56</td><td>6</td></tr>
</tbody>
</table>

2 个答案:

答案 0 :(得分:0)

所以你想要查看表头和第一个单元格。

也许这对你有用:

http://jsfiddle.net/MM5un/

HTML

<table class="display">
    <thead>
        <tr>
            <th>Hello 1</th>
            <th>Hello2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 - Cell 1</td>
            <td>Row 1 - Cell 2</td>
        </tr>
        <tr>
            <td>Row 2 - Cell 1</td>
            <td>Row 2 - Cell 2</td>
        </tr>
    </tbody>
</table>

<div class="showFirstTD"></div>
<div class="tableHeader"></div>

JS

var tableHeader = $('.display thead').html();

$('.display tbody tr').on('click',function(){
    $('.showFirstTD').html($(':first-child', this).text());
    $('.tableHeader').html(tableHeader);
});

答案 1 :(得分:0)

这是你要求的吗? http://jsfiddle.net/sXFRu/

<强> HTML:

<table class="items" id="mytable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Last Name</th>
      <th>City</th>
      <th>State</th>
    </tr>
  </thead>
  <tbody>
    <tr class="odd">
      <td>Joe</td>
      <td>Doe</td>
      <td>Boston</td>
      <td>MA</td>
    </tr>

    <tr class="even">
      <td>John</td>
      <td>Smith</td>
      <td>New York</td>
      <td>NY</td>
    </tr>    
  </tbody>
</table>

<强> jQuery的:

var tds = $('#mytable').find('td');
var ths = $('#mytable').find('th');
var td;


$('#mytable').on('dblclick', 'td', function() {
   td = $(this);

   tds.removeClass('highlight');
   ths.removeClass('highlight');

   td.addClass('highlight');
   ths.eq(td.index()).addClass('highlight');
});