針對全文透過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,644 Responses

  1. With havin so much written content do you ever run into any problems of plagorism or copyright violation? My site has a lot of exclusive content I’ve either created myself or outsourced but it seems a lot of it is popping it up all over the internet without my permission. Do you know any solutions to help prevent content from being stolen? I’d definitely appreciate it.

  2. Trefayx表示:

    Привет, друзья!
    Как приобрести диплом техникума с минимальными рисками
    rf-4fun.ru/index.php?/topic/324-удача-или-упорство/#comment-3555
    Рады оказать помощь!.

  3. Lazrgdm表示:

    Здравствуйте!
    Мы предлагаем дипломы любых профессий по доступным тарифам.
    symerechnaya.borda.ru/?1-16-0-00001090-000-320-1

  4. KevinSounc表示:

    http://denemebonusuverensiteler.win/# bonus veren siteler

  5. Mazrwah表示:

    Привет!
    Покупка диплома о среднем полном образовании: как избежать мошенничества?
    djarena.ru/index.php?links_exchange=yes&page=1&show_all=yes

  6. Uazriyx表示:

    Здравствуйте!
    Заказать диплом о высшем образовании.
    telegra.ph/diplom-tehnikuma-kupit-08-13-5

  7. Займы в интернете в одном месте — это возможность с all-credit.ru. Мы собрали лучшие варианты от МФО, как доверенных, так и перспективных, все они состоят в “Реестре ЦБ РФ”. Процентная ставка не больше 0,8% в день, что обеспечивает наши предложения выгодными для всех категорий граждан.

    Займы — это быстрый способ получить деньги, когда они срочно нужны. В отличие от кредитов, займы проще в регистрации и не нуждаются в долгих проверок. Вы можете полагаться на all-credit.ru, потому что мы отбираем только доверенные организации, гарантируя безопасность и высокие шансы на одобрение.

    Оформите взять микрозайм онлайн срочно без отказа и разрешите свои финансовые вопросы с минимумом трудностей. Все займы, представленные на all-credit.ru, обеспечивают удобство и скорость получения средств, что особенно существенно в срочных случаях. Надежность нашего сайта доказана временем и оценками пользователей.

  8. Lazrfvz表示:

    Привет!
    Мы предлагаем дипломы психологов, юристов, экономистов и прочих профессий по приятным тарифам.
    garagesale.es/author/elliottoxle

  9. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your website? My blog is in the exact same niche as yours and my visitors would truly benefit from a lot of the information you present here. Please let me know if this ok with you. Many thanks!

  10. JesusLealt表示:

    slot casino siteleri: slot casino siteleri – bonus veren slot siteleri

  11. Онлайн займы в одном месте — это возможность с all-credit.ru. Мы объединили лучшие варианты от МФО, как проверенных, так и молодых, все они зарегистрированы в “Реестре ЦБ РФ”. Процентная ставка не превышает 0,8% в день, что предоставляет наши предложения доступными для всех групп населения.

    Займы — это быстрый способ достать деньги, когда они нужны срочно. В отличие от кредитов, займы проще в оформлении и не нуждаются в долгих проверок. Вы можете верить all-credit.ru, потому что мы отбираем только проверенные МФО, гарантируя безопасность и вероятность одобрения.

    Оформите кредит на карту срочно без отказа и разрешите свои финансовые вопросы с минимумом трудностей. Все займы, доступные на all-credit.ru, обеспечивают простоту и мгновенность зачисления, что особенно значимо в неотложных моментах. Надежность нашего сайта проверена временем и отзывами пользователей.

  12. Darrelherse表示:

    deneme bonusu veren slot siteleri: slot siteleri guvenilir – deneme bonusu veren slot siteleri

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

  14. JesusLealt表示:

    deneme bonusu veren siteler: deneme bonusu veren siteler – bonus veren casino slot siteleri

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

  16. Lazrpod表示:

    Привет, друзья!
    Мы изготавливаем дипломы любых профессий по приятным тарифам.
    miranetwork.it/index.php?option=com_k2&view=itemlist&task=user&id=458652

  17. I have really learned new things through your blog post. One other thing I have seen is that generally, FSBO sellers will certainly reject you actually. Remember, they might prefer not to ever use your services. But if you actually maintain a gradual, professional romance, offering assistance and remaining in contact for four to five weeks, you will usually manage to win a conversation. From there, a house listing follows. Many thanks

  18. Займы в интернете в одном месте — это реальность с all-credit.ru. Мы подобрали лучшие варианты от МФО, как проверенных, так и молодых, все они зарегистрированы в “Реестре ЦБ РФ”. Процентная ставка не выше 0,8% в день, что делает наши предложения доступными для всех категорий граждан.

    Займы — это оперативное решение получить деньги, когда они срочно нужны. В отличие от кредитов, займы легче в получении и не нуждаются в долгих проверок. Вы можете доверять all-credit.ru, потому что мы отбираем только проверенные МФО, гарантируя безопасность и вероятность одобрения.

    Возьмите займ без отказа на карту онлайн и решите свои финансовые вопросы с минимумом трудностей. Все займы, доступные на all-credit.ru, дают простоту и скорость получения средств, что особенно существенно в экстренных ситуациях. Надежность нашего сайта доказана временем и мнениями клиентов.

  19. Mazrxvp表示:

    Здравствуйте!
    Легальная покупка диплома о среднем образовании в Москве и регионах
    grillbar163.ru/category/politika/page/2

  20. JesusLealt表示:

    bahis siteleri: bahis siteleri – deneme bonusu

  21. One other issue is that if you are in a circumstances where you do not have a cosigner then you may actually want to try to make use of all of your money for college options. You will find many grants and other grants that will supply you with funding to help with institution expenses. Thx for the post.

  22. GreggSib表示:

    This form of business can be chosen by different types of business entities such as trusts, corporations, and individuals. LLCs do not put the assets of their shareholders at risk by separating personal liabilities from those created by the company. The establishment of a limited liability company in Europe often requires the preparation of incorporation documents, the deposit of a minimum share capital, and registration with the Commercial Register. The management of the LLC is usually entrusted to the members (directors and shareholders), but in some cases the decision-making power in the company may be delegated from the founders of the business to hired managers.
    Opening an LLC in Europe offers many advantages, the most attractive of which is the limited liability of the owners. This means that in case something goes wrong, the owner will be liable for the company’s debts up to the amount of the authorised capital. Another important advantage of choosing a limited liability company is the capital that is required at incorporation. Many European countries have reduced the authorised capital requirements for this type of company. One of the best examples in this case is the Netherlands: those who want to open a Dutch limited company only need €1 as authorised capital. Of course, the total costs will be higher, but the Netherlands remains one of the cheapest European countries to start a company.

  23. GreggSib表示:

    kung saan sila ay naglalathala ng pinakabagong mga pagbabago sa batas ng mga bansang Europe sa larangan ng cryptocurrency at VASP (Virtual Asset Service Provider) para sa kaginhawahan at impormasyon ng lahat ng interesado sa batas ng cryptocurrency ng Europe. Batay kami sa aming mga artikulo sa mga paksa na mahalaga para sa mga negosyanteng nagtatrabaho sa larangan ng cryptocurrency, mga proyektong fintech, blockchain at negosyo na may kaugnayan sa IT. Kung hindi ninyo mahanap ang impormasyon na nais ninyo sa aming blog, mangyaring kontakin kami sa isang paraan na kagyat sa inyo.

  24. Have you ever considered about including a little bit more than just your articles? I mean, what you say is important and all. Nevertheless just imagine if you added some great visuals or video clips to give your posts more, “pop”! Your content is excellent but with pics and clips, this website could definitely be one of the greatest in its niche. Superb blog!

  25. Darrelherse表示:

    guvenilir slot siteleri: slot siteleri bonus veren – bonus veren slot siteleri

  26. GreggSib表示:

    Avrupa, dijital ortam? ve finansal yeniliklere ac?kl?g? sayesinde oncu is fikirleri icin bir merkez haline geldi. Geleneksel kurumsal s?n?rlar? genisletmeye ve dunya cap?ndaki musterilerimize yeni baslang?c f?rsatlar? sunmaya kararl?y?z. Amac?m?z, teknolojik yukselisi s?ras?nda Avrupa Birligi’nin s?n?rs?z olanaklar?ndan yararlanarak ve kusursuz is kararlar?n? bir t?k otede kolaylast?rarak uluslararas? ticarete deger katmakt?r.
    Tak?m cal?smas?
    Regulated United Europe‘da, cal?smalar?m?z?n etkililiginin her ekip uyesinin kolektif cabalar?na bagl? oldugunun bilincindeyiz. Vizyonumuz, musteriler, ortaklar ve meslektaslarla olan etkilesimin yonlendirdigi kars?l?kl? destek ve gunluk isbirligine odaklanmaktad?r. Gercekci hedefler belirlemenin, ekip kararlar?nda kurumsal sorumluluk ustlenmenin ve projeleri tamamlanana kadar gormenin onemini vurgulayarak kurumsal degerleri operasyonlar?m?z?n her yonune entegre ediyoruz.
    Bireysel yaklas?m

  27. biardiova表示:

    Figure 5e is corresponding to the degradation of starch treated in the presence of furosemide functionalized ferrite under alkaline and neutral pHs, respectively walmart priligy

  28. JesusLealt表示:

    sweet bonanza kazanma saatleri: sweet bonanza slot – sweet bonanza free spin demo

發佈留言

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