在页面中搜索文本(jQuery) - 如果不匹配该怎么办 [英] Search text in page (jQuery) - What to do if no match
本文介绍了在页面中搜索文本(jQuery) - 如果不匹配该怎么办的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个伟大的功能,就像一个魅力。只要匹配,脚本就会突出显示内容中的单词。但是,如果没有结果与查询匹配,我似乎可以找到正确的代码来显示错误。
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.
这是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>
这是函数:
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.
谢谢!
推荐答案
让RegExp工作,所以我去了:包含。它很棒。我希望这可以帮助某人:
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+
我希望这有帮助。
这篇关于在页面中搜索文本(jQuery) - 如果不匹配该怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文