开发者

jQuery highlight the characters found by :contains text from an input box

I got this code: Link

I can highlight the chars of static text by this js:

$("li:contains('Content1')").each(function(){
    var content = "Content1";
    this.innerHTML = this.innerHTML.replace(content,"<span>"+content+"</span>")
})

The Content1 by a dynamic value : $("#main").val()

QUESTION: How can i highlight words found 开发者_运维问答with :contains and with the value from the input box


This is going to be a little dicey, but check this out.

Your issue was that as you adjusted the content, you'd no longer be able to check what the original content was. The best way around this is, at the beginning, store the original LI text in a data-attribute, and then use that for manipulation later on.

 $("li").each(function() {
   $(this).attr( 'data-original', $(this).text() );
   $(this).attr( 'data-original-l', $(this).text().toLowerCase() );
 });

We then need to adjust your selector to check this attribute (as opposed to the text value):

 $("li[data-original *= \"" + $("#main").val().toLowerCase() + "\"]")

which, e.g. will search li[data-original*="Harry Potter"], which is "any LI with an attribute "data-original" which contains "Harry Potter" (see here).

From there, we just need to tweak your replacement statement as follows:

 $(this).html($(this).data('original').replace(new RegExp(content, "i"), "<span class='highlight'>$&</span>"));

We are doing the same thing you had originally, but now using the $(this).data('original') value instead of $(this).val(). We are also using a Regular Expression so that we can do the replacement case-insensitive. Also, we replace with $& which contains the match from the RegExp test in the original string.

Easy as pie! Hope this works for you and let me know if you run into any snags.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜