开发者

highlite text parts with jquery, best practice

i have a list of items containig names. then i have a eventlistener, which ckecks for keypress event. if the user types i.g. an A all names starting with an 开发者_Python百科A should be viewed with the A bold. so all starting As should be bold.

what is the best way using jquery to highlite only a part of a string?

thanks for your help


Here's a function you can call during your keypress event to highlight a search string:

function Highlight(search)
{
    $('ul > li').each(function() {
        if (this.innerHTML.indexOf(search) > -1)
        {
            var text = $(this).text();
            text = text.replace(search, "<span id='highlight' style='font-weight: bold'>" + search + "</span>");
            $(this).html(text);
        }
        else
        {
            this.innerHTML = $(this).text();
        }
    });
}

Test html:

<ul id='list'>
    <li>Bob Jones</li>
    <li>Red Smith</li>
    <li>Chris Edwards</li>
</ul>

It's not quite as elegant as Pointy's answer, but it handles the matching strings requirement.


There are jQuery plugins to do text highlighting, but I've not seen one that highlights parts of words.

One possible solution would be to put all your names on the page with the first letter surrounded by a <span> tag, with a class:

<span class='A FL'>A</span>ugustine
<span class='C FL'>C</span>arlos

You can then use jQuery to fiddle with those by class name.

$('whatever').keypress(function(ev) {
  var k = e.which.toUpperCase();
  $('#textContainer span.FL').css('font-weight', 'normal');
  $('#textContainer span.' + k).css('font-weight', 'bold');
});

Note that bold characters are fatter than normal characters, so this is going to have a "wiggly" effect that your users might not like. You might consider changing color instead.


thanks for your help... i figured it out and the detailed resolution comes here:

    var communities = $('#mylist').find('.name');
    var temp_exp = new RegExp("^("+match_string+")","i");
    communities.each(function(i){
        var current = $(this);
        var name = current.text();
        name = name.replace(temp_exp, '<b>$1</b>');
        current.html(name);
    });

while all items have to have the class "name".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜