强制使用jquery显示表中的前5行

force the first 5 rows in a table to show with jquery

本文关键字:5行 显示 jquery      更新时间:2023-09-26

我为导入的xml数据写了一个问题show hide jquery表行,关于如何使用jquery显示隐藏一些表行,现在使用相同的问题,我想知道如何强制显示前5个元素。我在示例中使用了以下代码:

$(document).ready(function(){
 $.ajax({
  type: "GET",
  url: "test.xml", 
  dataType: "xml",
  success: function(xml) {  
   $(xml).find('event').each(function(){    
    var Col0 = $(this).find('title').text();
    var Col1 = $(this).find('country').text();
    var Col2 = $(this).find('date').text();
    var Col3 = $(this).find('time').text();
    var Col4 = $(this).find('course').text();
    var Col5 = $(this).find('topic').text();
    var Col6 = $(this).find('pre-course').text();
    $('<tr></tr>').html('<th>'+Col0+'</th><td>'+Col1+'</td><td>'+Col2+'</td><td>'+Col3+'</td><td>'+Col4+'</td><td>'+Col5+'</td><td>'+Col6+'</td>').appendTo('#test');
 initalizeTable();  
 });
  }
 });
}); 

和html:

<table id="test">
       <tr><td></td><th>country</th>
        <th>Date</th><th>time</th>
         <th>course</th><th>topic</th>
          <th>pre-course</th></tr>
     </table>

然后我使用javascript只显示一些显示选项:

function initalizeTable() {
function show (min, max) {
    var $table = $('#test'), $rows = $table.find('tbody tr');
    min = min ? min - 1 : 0;
    max = max ? max : $rows.length;
    $rows.hide().slice(min, max).show();
    return false;    
}
$('#limit').bind('change', function () {
    show(0, this.value);
});
}

我必须包装上面的代码,将其包含在第一个代码中,以便在数据导入html后直接加载。

这是我用来手动更改显示选项的html:

<select id="limit">
    <option value="0">None</option>
    <option value="5"selected>5</option>
    <option value="10">10</option>
    <option value="15">15</option>
    <option value="20">20</option>
    <option value="" >All</option>
</select>

现在一切都很好,除了数据是在完整的表中导入的,我想强制只显示表中的前5行。

知道怎么做吗??

感谢

您可以在initalizeTable()函数结束时调用show(0,5);

或者在绑定后立即触发选择的更改事件,使其自动从下拉列表的当前选择选项中获取最大值:

$('#limit').bind('change', function () {
    show(0, this.value);
}).trigger('change');