2012-02-24 42 views
0

我在我的HTML中使用表格网格,并在每行中单击特定的col时,我使用<tr>动态创建了一行。附加行用于提交数据到服务器并在提交后将其删除。现在我想除此之外,表格的行号也将被发送到服务器。在使用jQuery时找出表中的元素(使用类)

因为我正在添加要编辑的行,因此表格会动态更改。我想通过给每个<tr>一个名为task_entry的类并通过计算.task_entry元素的数量来解决这个问题,我将能够找出我在哪一行。但是,我无法让这个工作。我试图使用$(".task_entry").index(this),但它返回-1。

任何人都可以帮忙吗?

+0

如果您要添加的行dinamically那么它将不会被JavaScript的回升。在这种情况下,您需要使用[jQuery live](http://api.jquery.com/live/) – Alfonso 2012-02-24 14:35:15

回答

1

不要使用.live(),因为它已被弃用。

请尝试打这个小提琴:http://jsfiddle.net/mB49c/1/

基于它的结构:

$(document).ready(function() { 

    $('table').on('click', 'td', function() { 

     //count the row. 0 based. If you want to start at 1, add 1 
     var my_row = $(this).parent('tr').index('table tr'); 

     $('table').append('<tr class="saving"><td>Col 1</td><td>Col 2</td><td>Col 3</td><td>Col 4</td><td>Col 5</td></tr>'); 


     alert('You clicked on row ' + my_row + ' run some code.. for instance AJAX'); 

     //If using AJAX, add this as a Success callback 
     $('.saving').remove(); 
    }); 
}); 
+0

谢谢,应该这样做。 – 2012-03-07 09:29:08

0
$(function() { 
    $("table td").click(function() { 
    var this_is = $(this).attr("id"); 
    var this_val = $(this).html(); 

    alert(this_val) 

    }); 
}); 
0

请检查你的情况是什么this。它可能是col,你点击?然后$(".task_entry").index($(this).closest('tr'))应该做的伎俩。