針對全文透過JS來做重點標示

在前陣子有個Case是要處理搜尋結果頁的部分,要將搜尋出來的內容利用關鍵字進行Highlight,所以有了下面這個範例,是利用正規表示法+JS進行處理,會無視搜尋關鍵字的大小寫,若要區分大小寫可將第45行中的gi,改為g就好,以下是範例頁面的Code,也可以直接連結到範例頁面試試看。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Highlight Text Sample</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style>
        .f-red{
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="input-group mb-3">
				<input type="text" id="hightlightText" value="我" class="form-control">
				<div class="input-group-append">
				<button class="btn btn-primary" type="button" id="activeBtn">Button</button>
			</div>
		</div>
		</div>
		<div id="content" class="row"></div>
	</div>
</body>
</html>
var htmlText = "";
$.ajax({
    url: "highLightText.txt",
    async: false,
    success: function(response){
        htmlText = response;
    }
});
$("#content").html(htmlText);

var hightlightText = $("#hightlightText").val();
$.fn.highlight = function(what,spanClass) {
    return this.each(function(){
        var container = this,
            content = container.innerHTML,
            pattern = new RegExp('([<.]*)(' + what + ')([<.]*)','gi'),
            replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
            highlighted = content.replace(pattern,replaceWith);
        container.innerHTML = highlighted;
    });
}
$('#content').highlight(hightlightText,'f-red');

$("#activeBtn").click(function(){
    $("#content").html(htmlText);
    var hightlightText = $("#hightlightText").val();
    $('#content').highlight(hightlightText,'f-red');
});
<p>給到王平銀日持風臺色營對合我過友的、造也在乎費靜臺白國:投無心面策一十人力委了可來沒?動區雲溫好面些、味又動高兒可來成的常他告臺布來處本我:界沒乎真不下老關,業實了種童不成他神舉經公黑下方、小利頭適不保講以心感校趣facebook不他到代易上海。一設開物愛研題來一下一國該要、機出又際各內案名相落的沒上年水部求沒山大式理密。房長裡再造級……童面費後務,風一也本名。太一息品的看統配北心他合情分子的經易民告只?</p><p>進安太,狀立?</p><p>文它接。於能病到腦反的題光,異卻道華找重有地北得了,去她定究愛,局自明加汽容看google及兒已的facebook兩:未不乎動常看選的所國半成著坐靈人一本成英一環處教時告即小!後也臺市開半:技月家,展教子、起構的相要從王排,臉外產便上。運自片同合可家小的部方單美哥人頭讀更外前喜民,有不馬的,你風的;心說火來的……全起飛事影。</p><p>拉為三參。體成和正地該名玩公可等Google學素母為收營……時世的回過高布家不生世存故研,為親總手?行眼長藝想海能和門新小認中日每收交金又成Facebook來而出還內界官我告展了戲有了的的?</p><p>由在下代保不著春原還其元上計一中合小,合的難修技空麼母於車當為下大灣的更吸如果中法照日目Facebook評一種父魚,目發體必詩遊完到往她數他來們標民。有西加邊,的已明得國多、的且看花性小下時都葉輪我後?觀復大物則的示的戰品照!失分量認法。而日媽運那麼個,名目石師越慢面我的古望科流身代安次野大的大深為坡打南發入定筆境產飛東資再變新西一滿價由親爭水道不合不性,google去實差來。球寶的了放車早大馬產場到使引是名最少不人經進人聲經光我,活連第,風軍工星費書它出。情會了每記、能時外社班們人第底月草。股本我google也。是不大日生未向心獲投時成到告平一樣爸音裡使上後讀如推其界明國報問小國快,打問盡自;裡物候小的了民品著家爭行全位?這時的足子一可等學讀不其今當前生好年點自星我藝資做精只基家他命方資前能一們?facebook美十本世高月有量用不善大一王毒跑們這們其可理出一樣規加還人和其寶再西因觀文葉態,灣木學定,個一知論參細已車不;但地口不別的務際千信記車南的、在營該科讓,我子機數年原是紅戰動感問象易一人所消登衣以他型新三。童愛早十以民國止最時構空夜包害石識小導開Google足活。都是身也個紙失八模用精想修速情不散靜到了小神幾會比找銷消之:行的結星才山風人地。山情資器產們這還上想明生。</p><p>調活前育她一來資!車各向進方加取而向成:使知過不,賽舉師皮;早而運星傳等之是法死技斯身不放facebook也日綠手上,不還國、紅球色統形不發過青展國,運市包,雜開基民場操造奇證;地的會沒工星人去,我作感影她創書處營器病……期有生寫看果公們工張,什館進因了入麼對體算兒低汽?靜但開目地、好久我期展今視義本:政義相會位例皮,加情地分朋學客助……年認校分存片常一是。</p><p>刻爾全否便,此前大檢生生回電性其供假調神約獎因突自阿的。</p>

實際動手玩看看↓↓

You may also like...

324,592 Responses

  1. GreggSib表示:

    The agreement allows for the exchange of information between other EU countries and Cyprus, even if the information is not required for tax purposes of these countries. However, the country from which the information is requested is not obliged to provide the information if it is a violation of the law or public interest of that country. It is also not allowed to request information that is not publicly available in that country.
    It should be noted that the Cypriot tax authorities in most cases do not have information on the beneficiaries of private companies or any other information material. For these reasons, Cypriot companies registered through nominees and information about the real owners is confidential.
    In this regard, persons whose information is withheld must be properly accumulated in the files of the registration agents. Professional secrecy cannot be used as an excuse for not providing information about these persons.
    However, the conditions under which professional secrecy may be lifted will depend on state law. Thus, disclosure will not be a simple automatic administrative procedure, but will require the intervention of local government officials.
    Opening a company in Cyprus can be a powerful step to expand your business and explore new markets. Because of its unique advantages, Cyprus offers great opportunities for growth and success in international business. However, success depends on careful planning, an understanding of the local business culture and effective resource management.

  2. Xazrips表示:

    Привет!
    Купить документ о получении высшего образования.
    Мы изготавливаем дипломы любых профессий по приятным ценам.
    sm100.ru
    Всегда вам поможем!.

  3. Treftpd表示:

    Привет, друзья!
    Пошаговая инструкция по официальной покупке диплома о высшем образовании
    bfintech.blogspot.com/2015/11/Buhgalterskij-balans-forma1-aktiv-passiv
    Окажем помощь!.

  4. GreggSib表示:

    Los abogados fintech y los asesores financieros de RUE (Regulated United Europe) han creado un blog en el que publican los ultimos cambios en la legislacion de los paises europeos en el ambito de la criptomoneda y el VASP (Virtual Asset Service Provider) para la comodidad e informacion de todos los interesados en la legislacion de la criptomoneda en Europa. Basamos nuestros articulos en temas que son importantes para los empresarios de hoy en dia que trabajan en el campo de la criptomoneda, proyectos fintech, blockchain y negocios relacionados con las TI. Si no encuentra la informacion que le interesa en nuestro blog, por favor, pongase en contacto con nosotros de la manera mas conveniente para usted.

  5. Experience fast and smooth gameplay on a Baccarat site optimized for all devices.

  6. KevinSounc表示:

    http://slotsiteleri.bid/# slot siteleri 2024

  7. Xazrjxl表示:

    Привет, друзья!
    Заказать документ института.
    Мы изготавливаем дипломы любой профессии по невысоким тарифам.
    nb12.ru
    Поможем вам всегда!.

  8. JesusLealt表示:

    canl? slot siteleri: deneme bonusu veren slot siteleri – en iyi slot siteleri

  9. Darrelherse表示:

    en iyi slot siteleri: deneme bonusu veren slot siteleri – oyun siteleri slot

  10. Sazrvwh表示:

    Привет!
    Диплом для вас
    telegra.ph/kupit-diplom-v-samare-s-zaneseniem-v-reestr-08-22-2

  11. Join a Baccarat site with a vibrant community of players and regular tournaments.

  12. Darrelherse表示:

    deneme bonusu veren siteler: en iyi slot siteleri 2024 – deneme veren slot siteleri

  13. Have you ever considered publishing an e-book or guest authoring on other blogs? I have a blog based on the same topics you discuss and would love to have you share some stories/information. I know my audience would value your work. If you are even remotely interested, feel free to shoot me an e-mail.

  14. bobbykk18表示:

    Videos for satan sex satanic sex ritual hypnotized cutscenes
    http://vibrating-bonn.danexxx.com/?yuliana-avery

    flash porn games under development ragnarok porn albino porn boyd laurence fishburne daughter porn viedo porn gag video

  15. JesusLealt表示:

    oyun siteleri slot: slot siteleri 2024 – en guvenilir slot siteleri

  16. Darrelherse表示:

    slot siteleri 2024: slot bahis siteleri – slot bahis siteleri

  17. Профессиональный сервисный центр по ремонту ноутбуков, макбуков и другой компьютерной техники.
    Мы предлагаем:ремонт macbook центр
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  18. GreggSib表示:

    SIF – Specialised Investment Fund A specialised investment fund based in Luxembourg is in principle exempt from income tax. The subscription tax is 0.01% per annum. The basis for calculating the subscription tax is the total net asset value of the specialised fund. The company is liable to a one-off capital tax of €1,250 payable on incorporation. SICAR – company with risk capital investments (Authorised capital of at least EUR 1mn) Annual capital turnover tax of EUR 1,250. Corporate tax 29.63%. There are no restrictions under double tax treaties. Profit distributions are not subject to source tax. Income from securities is exempt from tax. Proceeds from the liquidation of a company are not taxed (for non-resident participants)
    Luxembourg does not tax profits generated by offshore bank accounts. An offshore Luxembourg bank account is a guaranteed means of capital protection. All information in offshore bank accounts in Luxembourg is considered confidential and may not be disclosed without the express authorisation of the bank account holder.
    Luxembourg offers unique business opportunities due to its stable economy, favourable tax system, strategic location, quality financial services and high standard of living. These factors make it an attractive location for international investors and entrepreneurs seeking to expand their operations or enter the European market.
    However, business success in Luxembourg requires careful planning and understanding of the local environment. This includes choosing the best legal form for the company, strategic planning, complying with regulatory requirements and proactively engaging with local partners and regulators.
    Overall, Luxembourg offers a favourable environment for business development, backed by a highly skilled workforce, an innovative economy and a stable legal system.

  19. GreggSib表示:

    In Malta, it is possible to incorporate a closed and a public limited company. The minimum share capital of a public company is €46600 and €1200 for a private company. At the time of incorporation, at least 25 per cent of the capital of a public limited company and 20 per cent of the capital of a private limited company must be paid up.
    Taxation
    Profits earned by a resident company, whether in Malta or abroad, are subject to income tax at the rate of 35%. However, Malta does not impose tax on dividends, interest and royalties remitted abroad (no withholding tax) and Malta has no transfer pricing or thin capitalisation rules.
    (transfer pricing-the sale of goods or services to interdependent persons at intracompany, non-market prices. They allow the redistribution of the total profits of a group of persons in favour of persons in lower tax states. This is the simplest and most common scheme of international tax planning aimed at minimising taxes paid;
    thin capitalisation – when the company’s activities are financed by borrowed funds).
    Value Added Tax is levied on the sale of goods, works and services in Malta. The VAT rate on the island is 18%. Some goods are subject to preferential rates of 5% (e.g. printed publications, hotel services) and 0% (medicines and foodstuffs). There is no property tax and there is no turnover tax on the transfer of shares in companies owned by non-residents. Malta also has no exchange control legislation and a Maltese company can conduct its economic activities in any currency in the world.

  20. Darrelherse表示:

    guvenilir slot siteleri: slot kumar siteleri – slot bahis siteleri

  21. hello!,I like your writing so much! proportion we keep in touch extra about your article on AOL? I need an expert on this space to solve my problem. May be that’s you! Looking ahead to look you.

  22. Darrelherse表示:

    slot oyun siteleri: yeni slot siteleri – en yeni slot siteleri

  23. Lazrhse表示:

    Привет, друзья!
    Мы изготавливаем дипломы любой профессии по приятным ценам.
    radio-fm.pro/radio/raznaya/10203-radio-impuls-fm

  24. CarlosIcefe表示:

    Tato platforma umoznuje sazeni na ruzne sportovni udalosti. Zakaznicka podpora je dostupna 24/7, aby vam pomohla s jakymikoli problemy. Muzete sazet na sve oblibene tymy a sportovce. Tento web nabizi take virtualni sporty a e-sporty. Tento online portal nabizi hry od prednich svetovych poskytovatelu. Sazeni v realnem case je jednou z hlavnich vyhod teto platformy. Platforma pravidelne pridava nove hry do sve nabidky. Melbet K dispozici jsou ruzne zpusoby vkladu a vyberu, ktere jsou bezpecne a rychle. V nabidce jsou take ruzne bonusy pro nove i stavajici hrace. Platforma poskytuje zive prenosy zapasu, coz zvysuje zazitek ze sazeni. Registrace vam otevre pristup k rade skvelych her a vyhod. Uzivatele si mohou uzit ruzne kasinove hry s vysokymi vyhrami. Na teto strance najdete skvele kurzy pro vsechny hlavni sporty. Registrace je jednoducha a rychla, takze muzete zacit sazet behem nekolika minut. Tento web nabizi pristup k siroke skale sportovnich udalosti a kasinovych her. Kazdy den jsou k dispozici nove sazkove prilezitosti.

  25. These are some of the most important issues we’ll face over the next few decades.

  26. Профессиональный сервисный центр по ремонту ноутбуков, макбуков и другой компьютерной техники.
    Мы предлагаем:ремонт ноутбуков apple москва
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。