2013-11-15 113 views
4

我試圖自動選擇數據第一次加載時沒有這樣做的第一行表。datatables選擇第一行onload

第一次加載表格時,如何自動選擇第一行表格? 此HTML不起作用:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title></title> 

    <style type="text/css" title="currentStyle"> 
      @import "DataTables/css/demo_page.css"; 
      @import "DataTables/css/demo_table.css"; 
    </style> 


    <script type="text/javascript" src="Datatables/js/jquery.js"></script> 
    <script type="text/javascript" src="Datatables/js/jquery.dataTables.js"></script> 

    <script> 

     var oTable; 
     var firstTime = true; 

     $(document).ready(function() { 

      $("#example tbody").click(function (event) { 
       $(oTable.fnSettings().aoData).each(function() { 
        $(this.nTr).removeClass('row_selected'); 
       }); 
       $(event.target.parentNode).addClass('row_selected'); 
      }); 

      oTable = $('#example').dataTable({ 
       "sScrollX": "500px", 
       "sPaginationType": "full_numbers", 

       "bServerSide": true, 
       "sAjaxSource": "services/data3.ashx", 
       "sServerMethod": "POST", 
       "fnDrawCallback": function (oSettings) { 
        if (firstTime) { 
         alert('DataTables has redrawn the table'); 
         oTable.$('tr:first').click(); 
         firstTime = false; 
        } 

       } 
      }); 


     }); 

    </script> 

</head> 
<body> 

    <table border="1" > 

     <tr><td>id</td><td><input type="text" /></td></tr> 
     <tr><td>name</td><td><input type="text" /></td></tr> 
     <tr><td>surname</td><td><input type="text" /></td></tr> 


    </table><br /> 

    <table id="example" border="1" class="display"> 
     <thead> 
      <tr> 
       <td>name</td> 
       <td>surname</td> 
       <td>id</td> 
      </tr> 

     </thead> 
     <tbody></tbody> 


    </table> 

</body> 
</html> 
+0

Use focus()。可能重複的[關於訪問權限集中在錶行TR](http://stackoverflow.com/questions/7103306/focus-on-table-row-tr-for-accessiblity) –

回答

2

oTable.$('tr:first')將引發一個錯誤 - $不是oTable的功能或屬性。

您必須使用

oTable.find('tbody tr:first').focus() 

因爲tr:first將返回<thead><tr>,而不是<tbody><tr>

我不認爲你默認情況下可以將整個<tr>集中在HTML中,所以你必須添加一些CSS到<tr>使焦點可見。像這樣

tr { 
    border:1px inset white; 
} 
tr.focused { 
    border:1px solid red; 
} 

oTable.find('tbody tr:first').addClass('focused'); 

他們被點擊時重點行的例子:

oTable.find('tbody tr').click(function() { 
    oTable.find('tbody tr').removeClass('focused'); 
    $(this).addClass('focused'); 
}); 

上述所有在這個小提琴 - >http://jsfiddle.net/vv7Sa/