如何使用jquery创建下拉菜单来增加html表格中要显示的行数

lc8prwob  于 2022-12-16  发布在  jQuery
关注(0)|答案(1)|浏览(168)
<select>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">20</option>
</select>

<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

//jquery
var $rows=$("table tbody tr").length;

我想要的是允许用户选择显示更多行(如果有),并且如果存在10行以上,则在表中默认显示10行

liwlm1x9

liwlm1x91#

使用slice(option-start, option-end)显示/隐藏下拉菜单更改时所需的表行。
示例:

var deault_value = 1; // in your case default value is 10
var $rows = $("table tbody tr")
var $fotter = $("table tfoot tr")
$rows.hide();
$fotter.hide(); // if needed show footer , it's depend upon how you calculate summ
$rows.slice(0, 1).show(); // in your case show by default 10

$("select").change(function() {
  var num = $(this).val();
  $rows.hide();
  $($rows).slice(0, num * deault_value).show();
// Show fotter with calculation if needed. 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option value="1">1</option>
  <option value="2">2</option>

</select>

<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

相关问题