开发者

jquery - get td element in table

开发者 https://www.devze.com 2022-12-17 04:12 出处:网络
I would like to click on a anchor tag (a href) in a table and extract the contents of the ne开发者_JAVA技巧xt cell (or any specifc cell in that row)

I would like to click on a anchor tag (a href) in a table and extract the contents of the ne开发者_JAVA技巧xt cell (or any specifc cell in that row)

$(".clCode").click(function(){
    alert( $(this).text() );
    return false;
});

<table>
<tr>
<td class='clCode'><a href="#">Select</a></td><td>Code123</td>
</tr><tr>
<td class='clCode'><a href="#">Select</a</td><td>Code543</td>
</tr><tr>
<td class='clCode'><a href="#">Select</a</td><td>Code987</td>
</tr>
</table>


$(".clCode").click(function(){
    alert( $(this).parent().next().text() );
    return false;
});

That should get the next td. You can also pass a selector to next() if there are more tds and you want to get something other than the first one.

$(".clCode").click(function(){
    alert( $(this).parent().next(':last').text() );
    return false;
});


Getting the text from the next cell over is pretty straight forward:

$("td.clCode a").click(function(e){
  e.preventDefault();
  var nextText = $(this).parent().next().text();
});

Getting the text from another cell can be done by its index in the surrounding table-row:

$("td.clCode a").click(function(e){
  e.preventDefault();
  // Get text from fourth table-cell in row.
  var cellText = $(this).closest("tr").find("td:eq(3)").text();
});


$("td.clCode a").click(function() {
  var code = $(this).parent().next().text();
  alert(code);
  return false;
});


$(".clCode a").click(function() {
    alert($(this).parent().next().html();
    return false; // optional
});

I think your HTML markup is a little bit redundant.


you can use the jquery next() function to get a list of siblings:

$(".clCode").click(function(){
    tmp = $(this).next()[0];
    alert($(tmp).text());
});
0

精彩评论

暂无评论...
验证码 换一张
取 消