1. 程式人生 > >jQuery實現搜尋內容高亮顯示

jQuery實現搜尋內容高亮顯示

<html>

	<head>
		<meta charset="UTF-8">
		<title>jQuery搜尋高亮顯示</title>
	</head>

	<body>
		<input type="text" id="searchContent" placeholder=" 輸入要搜尋的書名" style="width:200px" class="input-text">
		<table>
			<tr>
				<th>書名</th>
				<th>作者</th>
				<th>出版社</th>
				<th>出版日期</th>
				<th>頁數</th>
				<th>價格</th>
				<th>內容摘要</th>
				<th>操作</th>
			</tr>
			<c:forEach items="${bookList }" var="book">
				<tr>
					<td class="highlightRow">${book.name }</td>
					<td>${book.author }</td>
					<td>${book.publish }</td>
					<td>
						<fmt:formatDate value="${book.publishdate}" pattern="YYYY-MM-dd" />
					</td>
					<td>${book.page }</td>
					<td>${book.price }</td>
					<td>${book.content }</td>
					<td>
						<a href="edit.html?id=${book.id }">修改</a>&nbsp;
						<a href="javascript:void(0)" onclick="del(${book.id})">刪除</a>
					</td>
				</tr>
			</c:forEach>
		</table>
		<script src="js/jquery-1.7.2.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript" charset="utf-8">
			//1.獲取要高亮顯示的行
			var rowNode = $('.highlightRow');
			//2.獲取搜尋的內容
			var searchContent = $("#searchContent").val();
			//3.遍歷整行內容,新增高亮顏色
			rowNode.each(function() {
				var word = $(this).html();
				word = word.replace(searchContent, '<span style="color:red;">' + searchContent + '</span>');
				$(this).html(word);
			});
		</script>
	</body>

</html>