jQuery - 在表格中的<tr>元素上绑定点击事件并获取<td>元素的值

39

我在一个 JSP 文件中有以下的 HTML 代码:

<div class="custList">
   <table class="dataGrid">
      <c:forEach var="cust" items="${custList}">
         <tr>
            <td>${cust.number}</td>
            <td>${cust.description}</td>
            <td>${cust.type}</td>
            <td>${cust.status}</td>
        </tr>
     </c:forEach>
  </table>
</div>
我需要能够在动态创建的<tr>标签上触发'click'事件,并且还要能够从JavaScript函数内访问所点击<tr>标签的<td>标签的值。我已经有了这个函数,但不幸的是它似乎没有起作用。
$(document).ready(function() {
    $("div.custList > table > tr").live('click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});
更新 (2016年1月):jQuery.live已被弃用(如此处所示:http://api.jquery.com/live/

从jQuery 1.7开始,.live()方法已被弃用。使用.on()来绑定事件处理程序。

7个回答

38

除非另有定义(<tfoot><thead>),否则浏览器会将<tr> 隐含地放在<tbody>中。

> table> tr之间需要插入> tbody

$("div.custList > table > tbody > tr")

另外,您还可以在选择行时放宽一些限制(> 表示 直接 子项):

$("div.custList table tr")
即便如此,你可以通过 $(this).children('td') 来获取其中的直接子元素 <td>

不知道关于插入<tbody>标签的事情。感谢帮助,非常好用。 :) - Randall Kwiatkowski
另外,如果您想获取至少有1个td的表行,请使用以下代码:$("div.custList table tr:has(td)").click(function () { //Code here }); 这将帮助您跳过第一行表头。 - Max

22

尝试使用jQuery的delegate()函数,例如:

$(document).ready(function(){
    $("div.custList table").delegate('tr', 'click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

委托(Delegate)的工作原理与 live() 相同,只是 live() 不能应用于链式项,而 delegate() 允许您指定要作用的元素中的一个元素。


3
自jQuery 1.7版本起,.delegate()方法已被.on()方法所替代。 - azerafati
这个答案(包括@Bludream的更新)是绑定事件最有效的方法,因为你不需要为每个tr绑定,只需要在父元素上绑定(在我们的情况下是table)。 - Shahar G.

12

这对我起作用了!

$(document).ready(function() {
    $(document).on("click", "#tableId tbody tr", function() {
        //some think
    });
});

6

由于TR元素包裹着TD元素,所以实际上你点击的是TD(然后它会冒泡到TR),因此你可以简化你的选择器。这样获取值也更容易,被点击的TD元素是this,包裹它的TR元素是this.parent。

将你的javascript代码更改为以下内容:

$(document).ready(function() {
    $(".dataGrid td").click(function() {
        alert("You clicked my <td>!" + $(this).html() + 
              "My TR is:" + $(this).parent("tr").html());
        //get <td> element values here!!??
    });
});​

5
$("body").on("click", "#tableid tr", function () {
    debugger
    alert($(this).text());
});

$("body").on("click", "#tableid td", function () {
    debugger
    alert($(this).text());
});

2

$(this).find('td')会返回tr中所有td的数组。


2
请注意,这也将返回任何嵌套表格的所有<td>children()返回直接子元素,就像$(this).find('> td')一样。 - BalusC

-3
<script>
jQuery(document).ready(function() {
    jQuery("tr").click(function(){
       alert("Click! "+ jQuery(this).find('td').html());
    });
});
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接