1. 程式人生 > >jquery高亮顯示搜尋的關鍵字

jquery高亮顯示搜尋的關鍵字

這種需求可以用js實現,可以用jquery實現,殊不知jquery有現成的外掛,親,你不用自己實現了,只需要引入jquery-hightlight.js

<!DOCTYPE html>
<html>
  <head>
    <title>regex.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  	<script type="text/javascript" src="../jquery/jquery-1.11/jquery.min.js"></script>
  	<script type="text/javascript" src="../jquery/jquery-highlight/jquery-hightlight.js"></script>
  	<style>
  		.highlight {background-color: #FFFF88; }
  	</style>
  	<script>
  		$(function(){
  			$('#search').click(function(){
  				var key = $('#key').val();
  	  			if(key.length > 0) {
  	  				var body = $('#body');
  	  				body.removeHighlight();
  	  				body.highlight(key);
  	  			} else {
  	  				alert("請輸入關鍵字!")
  	  			}
  			});
  		});
  	</script>
  </head>
  <body>
  	<div>
  		<input id="key" type="text">
  		<input id="search" type="button" value="搜尋">
  	</div>
    <div id="head">
    	This is a test head!
    	<div>
    		input the search key.
    	</div>
    	<div>
    		click "搜尋" button.
    	</div>
    </div>
    <h1>如下是搜尋區域!</h1>
    <div id="body">
    	This is a test body!
    	<div>
    		This is a test, a test, test, tes, te, t!
    		Do you know and listen this test, I think you don't know this test!
    	</div>
    	<div>
    		這是一個簡答的測試,測試.
    		<p>你知道或者聽過這個測試嗎,我認為你沒有聽過這個測試!</p>
    	</div>
    	<div>
    		This is a test, a test, test, tes, te, t!
    		I know't know this test, yes, this test is a not famous test!
    		<p>Follow me test, to test the test! I don't know what do you say?</p>
    	</div>
    	<div>
    		<div>
	    		這是一個簡答的測試,測試.
	    		我不知道這個測試,是的,這不是一個註明的測試,
	    		<span>跟隨我,去測試這個測試,我都不知道我在說什麼!</span>
    		</div>
    	</div>
    	<div>
    		What do you say? test, only a test?
    		<p>你們說什麼呢?測試,一個測試?</p>
    	</div>
    </div>
  </body>
</html>