Highlight words inside the string

﹥>﹥吖頭↗ 提交于 2019-12-24 18:13:51

问题


I got certain string, and I want to highlight the substring typed in the text input.

Here is a fiddle: http://jsfiddle.net/rFGWZ/17/

It is working fine only , when I type the initial string, but when I type fe. 15 in the input, it doesn't highlight the 15 but 21 instead... it is always highlighting the numbers at the beggining, so could someone help me modify it, so it will highlight the string I type in the text input?


回答1:


You can use this :

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

instead of

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

Demo : http://jsfiddle.net/qgBt8/

EDIT : case insensitive version




回答2:


I would use a regular expression to solve this. This also takes into account case of characters.

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();
            }
        }
    });
});​


来源:https://stackoverflow.com/questions/12459734/highlight-words-inside-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!