1

以下のWebサイトからJavascript検索を使用しようとしていますが、単語の一部を入力するとテーブル行も返されるように、検索された正確な用語のみを返す方法があるかどうか疑問に思っていました.

すなわち。「ヒース」を検索すると、ヒースを検索した場合と同じ結果が返されます」、簡単な回避策はありますか?

スクリプト: 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 に答える