查找文本并高亮

让我们来看一下如何使用 jQuery 去查找或搜索一段文本并高亮它。

我是 jQuery 的忠实粉丝,喜欢它简介的语法。接下来让我演示一个示例:仅使用一行 jQuery 代码便可把搜索字段进行高亮。

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Search Text in jQuery from DevCurry.com</title>
<style type="text/css"> div { height: 50px; width: 150px; border: 1px solid blue; } </style>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSearch").click(function () {
$("div:contains('simple')").css("border", "4px solid blue");
});
});
</script>
</head>
<body>
<div id="divOne">DivOne. This is a simple looking DIV</div><br />
<div id="divTwo">DivTwo. This is another simple looking DIV</div><br />
<div id="divThree">DivThree. This is just a DIV</div><br />
<div id="divFour">DivFour. This is again a DIV</div><br />
<div id="divFive">DivFive. Yet another simple looking DIV</div><br />
<input id="btnSearch" type="button" value="Search" />
</body>
</html>
 

这里我们使用 jQuery 中的 contains 选择器来在被锁定的元素及这些元素的后代中进行特定字符的查找。

如果 div 标签内包含 “simple” 文本,那么该 div 标签将会被高亮:宽度变为 4px,这些只需要一行代码。

提示: contains() 是大小写敏感的

jquery search text

显示结果

jquery search text

改进版本:

$("div:contains('simple')"
).html($("div:contains('simple')"
).html().replace(/simple/g, "simple
"));        

改进自:http://www.phphosts.org/2011/02/jquery-find-text-and-highlight-elements/

本文是使用 B3log SoloVanessa 进行同步发布的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值