简体   繁体   English

查找表中的行

[英]Find Row in Table

I have the following setup 我有以下设置

http://jsfiddle.net/ZkeTD/2/ http://jsfiddle.net/ZkeTD/2/

On the click of the button, I want to read the row number entered in the textbox and highlight that row. 单击按钮后,我要阅读在文本框中输入的行号并突出显示该行。 Eg if user enters 4, highlight 4th row. 例如,如果用户输入4,则突出显示第四行。 If row number is invalid, alert user to enter valid number. 如果行号无效,则警告用户输入有效号。

$("#btn").click(function(){
    var num = $("#inp").val();
});

How do I find the row and highlight it? 如何找到并突出显示行?

Use :eq(...) selector: 使用:eq(...)选择器:

$("#btn").click(function(){
    var num = $("#inp").val();
    $("tr").css("background", "transparent");
    $("tr:eq(" + num + ")").css("background", "red");
});

tr:eq(0) will select the header row. tr:eq(0)将选择标题行。

JSFIDDLE JSFIDDLE

You can try this : 您可以尝试以下方法:

 $("#btn").click(function(){
     var num = parseInt($("#inp").val());
     if (num) {
         var row = $("#movie tr:nth-of-type(" + num + ") td");
         if (row.length == 0) {
             alert("Invalid row number");
         } else {
             row.css("background", "yellow");
         }
     } else {
         alert("Invalid row number");
     }
 });

Note that you should validate user entry (here with parseInt()) to avoid code injection or any kind of unexpected behavior. 请注意,您应该验证用户输入(此处使用parseInt()),以避免代码注入或任何形式的意外行为。

This fits a situation slightly different than yours, but it is an alternative approach. 这种情况与您的情况略有不同,但这是另一种方法。 It has a nice feature ( intentional bug? ) where it also works for names, release years, etc... 它有一个不错的功能(故意的错误?),它也可以用于名称,发行年份等。

jsFiddle: http://jsfiddle.net/digitalextremist/Q7HYE/ jsFiddle: http : //jsfiddle.net/digitalextremist/Q7HYE/

$(document).ready( function() {
    $("#btn").on( "click", function(){
        $("td").removeClass("highlight")
        var num = $("#inp").val();
        console.log( "search: " + num )
        if ( $("td:contains(" + num + ")").length > 0 )
            $("td:contains(" + num + ")").closest("tr").addClass("highlight");
        else
            alert("Not found.")
    });
})

CSS: CSS:

.highlight {
    background: #f00;
    color: #fff
}

Screenshot... 屏幕截图...

工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM