0

特定の文字列を取得したので、テキスト入力に入力された部分文字列を強調表示したいと思います。

ここにフィドルがあります:http://jsfiddle.net/rFGWZ/17/

最初の文字列を入力したときだけ正常に動作していますが、fe と入力したときだけです。15入力では強調表示されません15が、21代わりに...常に最初に数字が強調表示されるので、誰かがそれを変更するのを手伝ってくれるので、テキスト入力に入力した文字列が強調表示されますか?

4

2 に答える 2

2

これを使用できます:

firstCell.html(id.replace(value, '<span class=highlight>'+value+'</span>'));

それ以外の

firstCell.html($("<span />").addClass("highlight").text(id.slice(0, value.length)));
firstCell.append(id.slice(value.length, id.length));

デモ: http://jsfiddle.net/qgBt8/

編集:大文字と小文字を区別しないバージョン

于 2012-09-17T13:03:17.927 に答える
0

これを解決するには、正規表現を使用します。これは、文字の場合も考慮に入れます。

jsFiddle

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

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

            $row = $(this);
            var firstCell = $row.children("td:first");

            var id = $row.children("td:first").text();
            if (id.indexOf(value) === -1) {
                $row.children("td:first").text(id);
                $row.hide();
            }
            else {
                var re = new RegExp(value, "g"); //global replace
                firstCell.html(id.replace(re, "<span class=\"highlight\">" + value + "</span>"));//replace all instances of the characters
                $row.show();
            }
        }
    });
});​
于 2012-09-17T13:17:07.937 に答える