【问题标题】:Arranging The html Tables using Jquery使用 Jquery 排列 html 表
【发布时间】:2012-07-26 22:20:57
【问题描述】:

假设我有这张桌子:

<table class="table table-striped table-bordered table-condensed">
    <tr>
        <th><h1>Tracks</td></th>
    </tr>
    <tr>
        <th>Track Id</th>
        <th>Artist</th>
        <th>Track Name</th>
        <th>Uploader</th>
        <th>Status</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Artist 1</td>
        <td>Track Name 1</td>
        <td>Uploader 1</td>
        <td>Blocked</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Artist 2</td>
        <td>Track Name 2</td>
        <td>Uploader 2</td>
        <td>Visible</td>
    </tr>
</table>

通过 JQuery 如何根据值排列表行?假设我想显示仅包含表数据值的表行。我将如何通过 Jquery 做到这一点?

【问题讨论】:

  • 好吧,如果您指定要使用哪种过滤器,以及该过滤器的最终结果(鉴于上述代码似乎没有“数据值”),那么这将有助于我们为您提供答案,而不仅仅是猜测。
  • 表数据值到底是什么意思,tr 中的第一个td 是否包含数字或其他某种值,现在很难理解是什么这是你想要做的吗?
  • 这是一个 包含我在搜索框中键入的数字或任何值的地方。假设我只搜索具有 Visible 的 它只会返回行或 具有包含值“Visible”的
  • 你愿意使用plugin吗?
  • 如果我不使用任何插件就更好了

标签: javascript jquery html html-table jquery-selectors


【解决方案1】:

这是一个例子:

$('#search').on('keyup', function() {
    var val = $.trim(this.value).toLowerCase();
    $('table > tbody > tr:gt(1)').hide();
    if (val.length) {
        $('table > tbody > tr:gt(1) > td').filter(function() {
            return this.innerHTML.toLowerCase().indexOf(val) >= 0;
        }).parent().show();
    } else  $('table > tbody > tr:gt(1)').show();
});

(这会给你一些指导)

Demo


相关参考文献:

【讨论】:

  • 这是做什么的? "$('table > tbody > tr').hide();" ?
  • @user962206 它隐藏了所有trs(表的直接子代)?我改变了这一点。不是它会隐藏所有trs 接受第一个Track
  • 它还隐藏了表头
  • @SperanskyDanil 使用.each() 两次速度较慢
  • @user962206 它将选择索引大于1 的所有tr,我分享必要的链接,检查它们,你会得到答案,伙计
【解决方案2】:

作为变体 (DEMO):

HTML

<input id="search" type="text">

<table id="table" class="table table-striped table-bordered table-condensed">
    <tr>
        <th>Track Id</th>
        <th>Artist</th>
        <th>Track Name</th>
        <th>Uploader</th>
        <th>Status</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Artist 1</td>
        <td>Track Name 1</td>
        <td>Uploader 1</td>
        <td>Blocked</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Artist 2</td>
        <td>Track Name 2</td>
        <td>Uploader 2</td>
        <td>Visible</td>
    </tr>
</table>

​JavaScript

$(document).ready(function () {
    $('#search').keyup(function () {
        $('#table tr').show();
        var q = $(this).val().toLowerCase();

        $('#table tr:not(:first)').each(function () {
            var visible = false;

            $('td', this).each(function () { 
                var content = $(this).text().toLowerCase();                    
                if (content.indexOf(q) != -1) visible = true;
            });

            $(this).toggle(visible);
        });
    })
});​

DEMO

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签