2016-08-17 87 views
0

我已經使用數據表作爲表。數據表搜索單擊元素

$('#tableid').dataTable({ 
    "aLengthMenu": [ 
    [2, 5, 7, -1], 
    [2, 5, 7, "All"] 
    ], 
    "iDisplayLength": 5 
}); 

和我如果點擊任何div元素我希望在數據表中搜索div元素的值。

<div id="search> 
    <a href="">this</a> 
</div> 

如果我點擊這個'''在表中搜索',這可以實現?

$(document).on('click','#search',function(e) 
{ 
    e.preventDefault(); 
    var search=$('#search').val(); 

} 
+0

什麼是你正在使用的數據表的版本? –

+0

version1.10.12是。 @palaesн – Steve

回答

1

使用搜索()的數據表功能來搜索手動

<script> 
     var table = $('#tableid').dataTable({ 
      "aLengthMenu": [ 
      [2, 5, 7, -1], 
      [2, 5, 7, "All"] 
      ], 
      "iDisplayLength": 5 
     }); 

$(document).on('click','#search',function(e) 
    { 
     e.preventDefault(); 
     var search =$('#search').text(); 
     table.search(search).draw(); 
    } 
</script> 

    <div id="search> 

    </div> 
+0

:) davidkonrad(向你學習) –

+0

它給了我錯誤。 table.search不是一個函數。 – Steve

+1

@Steve,因爲你已經用'dataTable()'初始化了,所以用'DataTable()'代替 - 如果你需要jQuery對象,你可以使用'table.api()。search()'... – davidkonrad

1
<script type="text/javascript"> 
    $(document).ready(function() { 
     var table = $('#example').DataTable({// or .dataTable({ for version under 1.10 
      "aLengthMenu": [ 
       [2, 5, 7, -1], 
       [2, 5, 7, "All"] 
      ], 
      "iDisplayLength": 5 
     }); 
     // it is more efficient to bind the click event not on body rather only on the needed elements 
     // you can use class name for selector if you want to use it on more divs 
     $('.search').click(function(e) 
     { 
      e.preventDefault(); 
      // you need to trim the given value because it can contain whitespace characters which can result false filtering 
      var search = $.trim($(this).text()); 
      table.search(search).draw(); 
     }); 
    }); 
</script> 
<div class="search"> 
    <a href="#">this</a> 
</div> 
<div class="search"> 
    <a href="#">that</a> 
</div>