Search text in page (jQuery) - What to do if no match

狂风中的少年 提交于 2019-12-11 18:53:12

问题


I have this great function that works like a charm. The script highlights the words in the content as long as it matches. However, I can seem to find the right code to display an error if no result matches the query.

This is the HTML:

<div id="search">
    <input type="text" id="searchtxt" />
    <input type="button" value="Find" onClick="replaceText();" id="search-resultButton" />
</div>

<p>Copy goes here</p>

And this is the function:

function replaceText() {
    $("body").find(".search-result").removeClass("search-result");

    var searchword = $("#searchtxt").val();
    var filter = new RegExp("\\b"+searchword+"\\b", "ig");

    if(searchword!=""){        
        $("body").each(function( ) { 
            $(this).html($(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>")) ;
        });
    }
}

I guess I'm looking for something like:

if(searchword!=""){        
    $("body").each(function( ) { 
        $(this).html($(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>")) ;
    });
} else {
    alert(“There is no match”)
}

But I can't seem to find the way to write it. Any help would be appreciated.

Thank you!


回答1:


You have messed up quotes alert(“There is no match”). Chances are you just need to fix it so it uses normal quotes before there is any chance it will work:

alert("There is no match")

"“ <-- see how those look different

Oh, and I'm sure this isn't the best way. but you could check if the replaced contents are equal to the original contents, and if so there is no match.

var replaced = $(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>");
if ($(this).html() == replaced) {
     //error
 }
 else
    $(this).html(replaced) ;



回答2:


Couldn't get RegExp to work so I went with :contains. It works great. I hope this can help someone:

function replaceText() {
    $("body").find(".search-result").removeClass("search-result");

    var searchWord = $("#searchtxt").val();             

    $("body").each(function( ) { 
        $('.module').removeClass('highlight'); //Remove old search highlights
        $("h1 .last-name:contains('" + searchWord + "')").addClass("search-result");

        if ($(".search-result")[0]){                
            // Do something
        } else {
            // No Match
        }
    });
}

To solve the case sensitivity issue, I added:

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
}); // jQuery 1.8+

I hope this helps.



来源:https://stackoverflow.com/questions/24834410/search-text-in-page-jquery-what-to-do-if-no-match

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