开发者

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

开发者 https://www.devze.com 2023-03-28 04:21 出处:网络
I got this code: Link I can highlight the chars of static text by this js: $(\"li:contains(\'Content1\')\").each(function(){

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

精彩评论

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