1

我正在使用“实时”功能在表格行上做一些点击操作,即

$("tr").live('click',function() {
      alert('Some table row is clicked');
});

我想找出单击和使用哪一行,并if-else基于此给出一些自定义警报。谁能告诉我该怎么做?

非常感谢。

编辑1:

有没有办法可以引用函数内单击行的元素?

4

7 回答 7

6
$("tr").live('click', function() {
    if (this.id == "foo") {
        alert('the tr with the foo id was clicked');
    }
});​

如果要检查哪个行号,请使用index

$("tr").live('click', function() {
   if $(this).index() === 2) {
     alert('The third row was clicked'); // Yes the third as it's zero base index
   }
});​

现场演示


更新:

$("tr").live('click', function() {
    // "this" is the clicked <tr> element
    // $(this).find('td span') is the spans inside a td inside the clicked <tr>
}
于 2012-05-06T08:57:10.137 回答
2

First you shouldn't use .live() ever :)

why you shouldn't use .live()

you can use instead .delegate()
Example

$(document).delegate("tr", "click", function(e) {
 // write your code here 
});
于 2012-05-06T09:04:53.693 回答
2

Let me suggest an easy way. Suppose this is your table:

<table>
<tr id = '1' class="tr">...</tr>
<tr id = '2' class="tr">...</tr>
<tr id = '3' class="tr">...</tr>
</table>

Place this in your jQuery code:

$(function(){

$('.tr').click(function(){
var row_no = $(this).attr('id');
alert('Row number '+row_no+' was clicked');
});

});

Hope this helps you.

于 2012-05-06T09:09:38.527 回答
1

演示:http: //jsfiddle.net/zJUuX/

HTML:

<table>
    <tr><td>hey</td></tr>
    <tr><td>hi</td></tr>
</table>

查询:

$("table tr").click(function(){
    messages( $(this).index() );
});

    function messages(index) {
        switch(index){
            case 0:
                alert("you clicked 1st row");
                break;
            case 1:
                alert("you clicked 2nd row");
                break;
            default:
                break;
        }
        $("table tr").eq(index).css("background","#ff0");
        $("table tr").eq(index).find("a"); //will find all the nested anchor tags.
    }

好了,学习者,现在我将接受我的虚拟积分:D。玩得开心。

于 2012-05-06T09:02:10.727 回答
0

您可以使用 访问单击的元素this

offtopic : $.live 自 1.7 起已弃用,您应该使用 $.on。请参阅此处了解更多信息。

于 2012-05-06T09:01:59.030 回答
0

As an improvement on gdoron's answer jQuery's live() is deprecated, try delegate or on:

$("#mytable").delegate("tr", "click", function(e) {
  if (this == "foo") {
     ....
  }
});
于 2012-05-06T09:02:54.017 回答
-1
//Even row
$("tr:even").click(function() {
    alert('Even');
});

//Odd row
$("tr:odd").click(function() {
    alert('Odd');
});​
于 2012-05-06T09:02:45.123 回答