如何搜索页面内容中显示的文本? [英] How to search a text which is displayed in the page content?
本文介绍了如何搜索页面内容中显示的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< script type =text / javascript>
函数searchAndHighlight(searchTerm,selector){
if(searchTerm){
var selector = selector || 身体; //如果没有提供,则使用body作为选择器
var searchTermRegEx = new RegExp(searchTerm,ig);
var matches = $(selector).text()。match(searchTermRegEx);
if(matches){
$('.enpased')。removeClass('highlighted'); //删除旧的搜索精选
$(选择器).html($(选择器).html()
.replace(searchTermRegEx,< span class ='highlight'>+ searchTerm + < /跨度>中));
if($('。highlight:first')。length){//如果找到匹配,滚动到第一个出现的位置
$(窗口).scrollTop($('。highlight:first ).POSITION()顶部)。
}
返回true;
}
}
返回false;
}
$(document).ready(function(){
$('#btnSearch')。on(click,function(){
if(!searchAndHighlight) ($('#txtSearch')。val())){
alert(找不到结果);
}
});
});
< / script>
在上面的代码中,我搜索并突出显示了文本。但问题是如果我键入'in'它搜索整个页面内部html和图像(例如:-hidden fields,img name,inin< input type ==>)。
如何搜索网页中显示的页面内容或文本中的文本。
解决方案
(选择器)的.text()匹配(searchTermRegEx)。
if(matches){
('.enpated')。removeClass('highlighted'); //删除旧的搜索突出显示
(选择器).html(
<script type="text/javascript"> function searchAndHighlight(searchTerm, selector) { if (searchTerm) { var selector = selector || "body"; //use body as selector if none provided var searchTermRegEx = new RegExp(searchTerm, "ig"); var matches = $(selector).text().match(searchTermRegEx); if (matches) { $('.highlighted').removeClass('highlighted'); //Remove old search highlights $(selector).html($(selector).html() .replace(searchTermRegEx, "<span class='highlighted'>" + searchTerm + "</span>")); if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears $(window).scrollTop($('.highlighted:first').position().top); } return true; } } return false; } $(document).ready(function () { $('#btnSearch').on("click", function () { if (!searchAndHighlight($('#txtSearch').val())) { alert("No results found"); } }); }); </script>
In above code i have searched and highlighted the text. But issue is if i type 'in' it search whole page inner html and images(eg:-hidden fields,img name,"in" in <input type=="">).
How i search the text which is displayed in the page content or text displayed in web page.
解决方案
(selector).text().match(searchTermRegEx); if (matches) {
('.highlighted').removeClass('highlighted'); //Remove old search highlights
(selector).html(
这篇关于如何搜索页面内容中显示的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文