1

我正在尝试使用来自以下网站的 Javascript 搜索但是想知道是否有一种方法可以只返回搜索的确切术语,就好像我输入了一个单词的一部分,它也返回了表格行。

IE。搜索“Heath”返回与搜索 Hethesh 相同的结果,是否有简单的解决方法?

脚本: http ://heathesh.com/post/2010/05/06/Filtering-or-searching-an-HTML-table-using-JavaScript.aspx

示例: http ://heathesh.com/code/javascript/tablesearch/


<table border="1" cellpadding="0" cellspacing="0">
    <tr>
        <th>ID</th>
        <th>First Name</th>
        <th>Surname</th>
        <th>Website</th>
    </tr>
    <tbody id="data">
        <tr>
            <td>1</td>
            <td>Heathesh</td>
            <td>Bhandari</td>
            <td><a href="http://heathesh.com">http://heathesh.com</a></td>
        </tr>
        <tr>
            <td>2</td>
            <td>Candice</td>
            <td>David</td>
            <td><a href="http://candicedavid.com">http://candicedavid.com</a></td>
        </tr>
    </tbody>
</table>

//define the table search object, which can implement both functions and properties
    window.tableSearch = {};

    //initialize the search, setup the current object
    tableSearch.init = function() {
        //define the properties I want on the tableSearch object
        this.Rows = document.getElementById('data').getElementsByTagName('TR');
        this.RowsLength = tableSearch.Rows.length;
        this.RowsText = [];

        //loop through the table and add the data to the table search object
        for (var i = 0; i < tableSearch.RowsLength; i++) {
            this.RowsText[i] = (tableSearch.Rows[i].innerText) ? tableSearch.Rows[i].innerText.toUpperCase() : tableSearch.Rows[i].textContent.toUpperCase();
        }
    }

接下来创建实际的 JavaScript 函数来运行搜索,如下所示:

    //onlys shows the relevant rows as determined by the search string
    tableSearch.runSearch = function() {
        //get the search term
        this.Term = document.getElementById('textBoxSearch').value.toUpperCase();

        //loop through the rows and hide rows that do not match the search query
        for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
            row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
        }
    }

    //handles the enter key being pressed
    tableSearch.search = function(e) {
        //checks if the user pressed the enter key, and if they did then run the search
        var keycode;
        if (window.event) { keycode = window.event.keyCode; }
        else if (e) { keycode = e.which; }
        else { return false; }
        if (keycode == 13) {
            tableSearch.runSearch();
        }
        else { return false; }
    }

<table border="0" cellpadding="0" cellspacing="0">
    <tbody>
        <tr>
            <td>
                <input type="text" size="30" maxlength="1000" value="" id="textBoxSearch" onkeyup="tableSearch.search(event);" />
                <input type="button" value="Search" onclick="tableSearch.runSearch();" />
            </td>
        </tr>
    </tbody>
</table>
4

2 回答 2

1

rowText.indexOf()在下面的代码中将其与此匹配,如果在字符串中的任何位置找到该术语,它将返回该行。

for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
    row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
}

要获得完全匹配,请更改rowText.indexOf(this.Term) != -1rowText.toUpperCase() === this.Term.toUpperCase(). 在比较之前将.toUpperCase()两个字符串都转换为大写,以使搜索不区分大小写。

for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
    row.style.display = ((rowText.toUpperCase() === this.Term.toUpperCase()) || this.Term === '') ? '' : 'none';
}
于 2013-04-19T06:30:12.120 回答
0

如果完全匹配的单词没有给出任何结果,以下代码将进行部分搜索:

<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Search table</title>
</head>
 <body style="  background-color:white;">
<input type="text" size="30"
 value="" 
 id="textBoxSearch" 
 onkeyup="tableSearch.search(this.value);" />
<div id="table"></div>
<script type="text/javascript">
// create a 4 column table with random text
function getRandomText(len){
    ret=[];
    for(var i =0;i<len;i++){
        ret.push(String.fromCharCode(
          Math.floor((Math.random()*(85-65))+65)
        ));
    }
    return ret.join("");
}
function createRandomTable(){
    var ret=["<table>"],i=0,
    j=0;
    while(i<50){
        j=0
        ret.push("<tr>");
        while(j<5){
            ret.push("<td>");
            ret.push(getRandomText(5));
            ret.push("</td>");
            j++;
        }
        ret.push("</tr>");
        i++;
    }
    document.getElementById("table")
     .innerHTML=ret.join("");
} 
createRandomTable();
// Code that does the search
tableSearchF=function(){
    //private variables
    var table=document.getElementById("table")
      .getElementsByTagName("table")[0];
    var rows=table.getElementsByTagName("tr");
    var rowVals=[];
    for(var i=0;i<rows.length;i++){
        var tmp=[];
        var c=rows[i].getElementsByTagName("td");
        for(var j=0;j<c.length;j++){
            tmp.push(
              (c[j].textContent)?c[j].textContent:c[j].innerText
            )
        }
        rowVals.push(tmp);
    }
    var searchTable=function(r){
        var match=false;
        var doPartial=true;
        // for each row
        for(var i=0;i<rowVals.length;i++){
            match=false;
            //for each cell
            cellmatch:
            for(var j=0;j<rowVals[i].length;j++){
                if(r.test(rowVals[i][j])===true){
                    console.log("positive match");
                    match=true;
                    doPartial=false;
                    break cellmatch;
                }
            }
            rows[i].style.display=(match)?"":"none";
        }
        return doPartial;
    }
    // publicly available methods
    return {
        search:function(searchText){
            var txt = searchText.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g
              ,'\\$1')
              .replace(/\x08/g, '\\x08'),
            r = new RegExp("\\b"+txt+"\\b","igm");
            if(searchTable(r)){
                // no exact match, do a partial
                r=new RegExp(txt,"igm");
                searchTable(r);
            }
        }
    }
}
//initialise tableSearch
var tableSearch=tableSearchF();
</script>

 </body>
</html>
于 2013-04-19T06:31:21.823 回答