jquery 搜索适用于一列而不是整个 html 表

标签 jquery

只想使用 jquery 添加对加载表的搜索可能性,但下面的代码仅适用于第一列。我想让它适用于所有细胞。您能检查一下代码并帮我找出错误吗:

这是我的 html 代码:

<span id="search"></span>

这是我的js代码:

$("#search").on("keyup", function () {
    var value = $(this).text();

    $("table tr").each(function (index) {
        if (index != 0) {

            $row = $(this);

            $row.each(function () {

                var cell = $row.find("td").text();

                if (cell.indexOf(value) != 0) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        }
    });
});

最佳答案

我认为您不需要执行 $row.each 因为您已经在每个中,请尝试在列上执行每个:

$("#search").on("keyup", function () {
    var value = $(this).text();

    $("table tr").each(function (index) {
        if (index != 0) {

            $row = $(this);

            $row.find("td").each(function () {

                var cell = $(this).text();

                if (cell.indexOf(value) != 0) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        }
    });
});

编辑:

http://jsfiddle.net/rn8dsnwm/2/

$("#search").keyup(function () {
    var value = $(this).val();

    if (value.length){
        $("table tr").each(function (index) {
            if (index != 0) {

                $row = $(this);

                $row.find("td").each(function () {

                var cell = $(this).text();

                if (cell.indexOf(value) < 0) {
                    $row.hide();
                } else {
                    $row.show();
                    return false; //Once it's shown you don't want to hide it on the next cell
            }

        });
    }
});
}
else{
    //if empty search text, show all rows
    $("table tr").show();

}
});

关于jquery 搜索适用于一列而不是整个 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191358/

相关文章:

javascript - 改变增量减量框

javascript - 在 Jquery 中查找字母数字字符串数组中的最大数字

javascript - css/javascript 元素在应该返回 true 时返回 false

javascript - 未捕获类型错误 : fn is not a function in chart. js

jquery - 用户更改后如何获取真实的输入值(使用 jQuery)?

javascript - 使用 Jquery 获取并遍历表中的所有选择框

javascript - 为什么 jquery UI 可拖动不适用于 getElementById

javascript - 替换字符串 Jquery

jquery - Highstocks(比较图表)不使用getJSON输入数据

validation - jQuery 表单验证和可用电子邮件检查