1
2
3
4
5
|
<style type=
"text/css"
>
.highlight {
background-color
: yellow;
}
</style>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
function
highlight() {
clearSelection();
//先清空一下上次高亮显示的内容;
var
searchText = $.trim($(
'#txtKeyWord'
).val());
//获取你输入的关键字;
if
(searchText.length > 0) {
var
regExp =
new
RegExp(searchText,
'g'
);
//创建正则表达式,g表示全局的,如果不用g,则查找到第一个就不会继续向下查找了;
$(
'#dialogue .dhc'
).each(
function
()
//遍历要查询的区域;
{
var
html = $(
this
).html();
var
newHtml = html.replace(regExp,
"<span class='highlight'>"
+ searchText +
'</span>'
);
//将找到的关键字替换,加上highlight属性;
$(
this
).html(newHtml);
//更新文章;
});
}
//prekeyword = searchText;
}
function
clearSelection() {
$(
'#dialogue .dhc'
).each(
function
()
//遍历
{
$(
this
).find(
'.highlight'
).each(
function
()
//找到所有highlight属性的元素;
{
var
thishtml = $(
this
).html();
$(
this
)[0].outerHTML = thishtml;
// $(this).replaceWith(thishtml); //将他们的属性去掉;
});
});
}
|