<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>
在上面的代码中,我搜索并突出显示了文本。但问题是如果我键入&#34;&#34;它搜索整个页面内部的HTML和图像。屏幕简称如下。
我如何搜索页面内容中显示的文本。
答案 0 :(得分:0)
<强>被修改强>
所以我想到的是p
,div
和span
是您应该在其中执行检查以查找子字符串的元素。
var search = ['p', 'div', 'span'];
var pattern = searchTerm;
$.each(search, function(i){
var str = search[i];
var orgText = $(str).text();
orgText = orgText.replace(pattern, function($1){
return "<span class='highlighted'>" + $1 + "</span>"
});
$(str).html(orgText);
});
});
答案 1 :(得分:0)