4

使用 JQuery,我需要知道用户点击的是链接还是第三列,并且需要获取第一列中变量的值。我该怎么做呢?

我的html:

<div id="test">
<table id="tablex" cellpadding="0" cellspacing="0" border="0" class="display">
    <thead>
        <tr>
            <th>Cod</th>
            <th>Name completo</th>
            <th>&nbsp;</th>
        </tr>
    </thead>
    <tbody>
         <tr>
             <td>1</td>
             <td>John Foster 1</td>
             <td><img entity_id="1" class="image-selector" src='imagens/grid_cancel.png' title=''  /></td>
         </tr>
    </tbody>
</table>

我的 jQuery:

$("#tablex tbody").on("click", "td", function(event){
   alert($(this).text());
});
4

3 回答 3

5
$("#tablex tbody").on("click", "td", function(event){
    alert($(this).index());
    alert($(this).siblings("td:first").text());
});

$(this).index()将为您提供单击列的从零开始的索引。 $(this).siblings("td:first").text()将为您提供第一列中的文本。

在这里,有一个小提琴:http: //jsfiddle.net/adrianonantua/EAEsG/

于 2012-10-31T17:29:02.340 回答
3

这将为您提供单击列的列号,以及第一列的值...

$("#tablex tbody").on("click", "td", function(event){
   var index = $(this).index();
   var col1value = $(this).parent().find("td").first().text();
});
于 2012-10-31T17:32:06.213 回答
0
 <script type="text/javascript">
  $(document).ready(function() {     
   $(".image-selector").on("click", function(event){
    var colvalue = $(this).parent().parent().find("td").first().text();
    alert(colvalue);
});  
 }); 
 </script>  

如果您希望它基于 TD 点击而不是图像点击,请将类移动到 td 而不是图像

然而,这是我认为更干净的选择,使用 HTML5 数据属性

HTML

  <td>1</td>
  <td>John Foster 1</td>
  <td><div data-value='1' class='image-selector'><img src='imagens/grid_cancel.png' title=''  /></div></td>

jQuery

 <script type="text/javascript">
  $(document).ready(function() {     
   $(".image-selector").on("click", function(event){
    var colvalue = $(this).data('value');
    alert(colvalue);
  });    
 }); 
 </script> 
于 2012-10-31T17:41:25.480 回答