开发者

Making the first N letters in a string bold?

I am trying to make an autocomplete form that will bold the letters in the results as you type.

The function I have made doesn't work:

function setBold () {   

 var text = $('input#auto_results').val();
 var text_length = text.length;

    e = $('.result').html();
    r = e.replace("<b>", "");
    d = r.replace("</b>", "");
    n = d.substr(0, text_length);
    q = n.bold(开发者_JS百科);
    r = d.length - text_length;
    m = d.substr(text_length, r);

    $('.result').html(q+m);
}

Because if you have multiple results:

<li class='result'>text</li>
<li class='result'>texter</li>
<li class='result'>textes</li>
<li class='result'>textli</li>
<li class='result'>textwe</li>

It replaces the text in the results with the bolded version of the first result.

I would just like how to bold the first N letters in a list:

<li class='result'>textes</li>
<li class='result'>textli</li>
<li class='result'>textwe</li>

Using javascript and/or jquery.


Use html() with the function callback, like this:

function setBold () {   

 var text = $('input#auto_results').val();
 var text_length = text.length;

    $('.result').html(function(i,e){
       r = e.replace("<b>", "");
    d = r.replace("</b>", "");
    n = d.substr(0, text_length);
    q = n.bold();
    r = d.length - text_length;
    m = d.substr(text_length, r); 
        return q+m;
    });
}

example: http://jsfiddle.net/niklasvh/rfwYb/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜