2011-08-04 36 views
0

我在gridview行中選擇一個文本框。 我知道一個gridview是一個html表。 我怎樣才能找出文本框所在的td是jQuery表中tr的最後一個td?檢查td是否與jQuery的最後一個相鄰

<asp:GridView runat="server"> 
<Columns> 
    <asp:TemplateField HeaderText="Standardpreis"> 
     <ItemTemplate> 
      <asp:TextBox runat="server" ID="valueTxt"></asp:TextBox> 
     </ItemTemplate> 
    </asp:TemplateField>    
</Columns> 

+0

您可以加入你的表結構, JavaScript的。 – Sparkup

回答

1

像這樣的事情在事件的子元素

var $that = $(this), 
    $td = $that.closest('td'), 
    trChildrenCount = $td.parent().children().length, 
    tdBeforeLast = trChildrenCount - 1, 
    tdIndex = $td.index() + 1; // get 1-based index 

if (tdBeforeLast === tdIndex) { 
    console.log('next to last td'); 
    // do stuff... 
} 

example jsfiddle

+0

謝謝,但索引總是-1,那是怎麼回事? – AGuyCalledGerald

+0

是您在''中觸發'keypress'的事件嗎?或事件發生在哪裏。 – MikeM

+0

是的,當點擊文本框中的返回 – AGuyCalledGerald

0

你可以做這樣的事情:

var td = $(selector); // The 'td' you want 
var tdLength = td.closest('tr').children('td').length; // Get the number of tds in the tr 
if(td.index()+1 == tdLength-1){ // Is it second to last (.index() is zero-based) 
} 

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

1
<script type="text/javascript"> 
    $(function() { 

     var $td = $("#second"); // swap this to #first to test 

      if ($td.index() === $td.siblings().length - 1) { 
       console.log("2nd last"); 
      } else { 
       console.log("not 2nd last"); 
      } 

    }); 
</script> 
<table> 
    <tr> 
     <td id="first">first</td> 
     <td id="second">second</td> 
     <td id="third">third</td> 
    </tr> 
</table> 

在您的例子,如果你正在尋找一個特定的文本框,它可能比較容易提上了一個文本框的CssClass,並查找其父母。在這種情況下,爲$ TD的選擇看起來像下面這樣:

var $td = $(".someTextBoxClass").closest("td"); 
0

的JavaScript

$('#test td').click(function(){ 

    var lng = $('td', $(this).parent().parent()).size(); 
var myIndex = $('td', $(this).parent().parent()).index(this); 
if(lng-1 == myIndex+1) 
    console.log('next to the last'); 
}); 

HTML

<table id="test"> 

    <tbody><tr><td>First Row</td></tr> 
    <tr><td>Middle Row</td></tr> 
    <tr><td>Last Row</td></tr> 

    </tbody></table> 
相關問題