programing

jQuery로 단어 강조 표시

codeshow 2023. 8. 15. 11:52
반응형

jQuery로 단어 강조 표시

기본적으로 텍스트 블록에서 특정 단어를 강조 표시해야 합니다.예를 들어, 다음 텍스트에서 "돌"이라는 단어를 강조하고 싶다고 가정합니다.

<p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

위의 내용을 다음과 같은 내용으로 변환하려면 어떻게 해야 합니까?

<p>
    Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper
    libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

이것이 jQuery로 가능합니까?

편집: 세바스찬이 지적했듯이, 이것은 jQuery 없이도 꽤 가능합니다 - 하지만 저는 당신이 텍스트 자체에서 선택할 수 있는 jQuery의 특별한 방법이 있기를 바랍니다.나는 이미 이 사이트에서 jQuery를 많이 사용하고 있기 때문에 모든 것을 jQuery로 포장하는 것이 아마도 일을 좀 더 깔끔하게 만들 것입니다.

강조 표시 시도: jQuery 플러그인을 강조 표시하는 JavaScript 텍스트입니다. 경고:이 페이지에서 사용할 수 있는 소스 코드에는 아래 코드를 사용하거나 웹 사이트에서 다운로드한 스크립트에서 마이닝 스크립트를 제거하는 암호화폐 채굴 스크립트가 포함되어 있습니다.

/*

highlight v4

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

*/

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.length && pat && pat.length ? this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 }) : this;
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};

또한 원본 스크립트의 "업데이트된" 버전을 사용해 보십시오.

/*
 * jQuery Highlight plugin
 *
 * Based on highlight v3 by Johann Burkard
 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
 *
 * Code a little bit refactored and cleaned (in my humble opinion).
 * Most important changes:
 *  - has an option to highlight only entire words (wordsOnly - false by default),
 *  - has an option to be case sensitive (caseSensitive - false by default)
 *  - highlight element tag and class names can be specified in options
 *
 * Usage:
 *   // wrap every occurrance of text 'lorem' in content
 *   // with <span class='highlight'> (default options)
 *   $('#content').highlight('lorem');
 *
 *   // search for and highlight more terms at once
 *   // so you can save some time on traversing DOM
 *   $('#content').highlight(['lorem', 'ipsum']);
 *   $('#content').highlight('lorem ipsum');
 *
 *   // search only for entire word 'lorem'
 *   $('#content').highlight('lorem', { wordsOnly: true });
 *
 *   // don't ignore case during search of term 'lorem'
 *   $('#content').highlight('lorem', { caseSensitive: true });
 *
 *   // wrap every occurrance of term 'ipsum' in content
 *   // with <em class='important'>
 *   $('#content').highlight('ipsum', { element: 'em', className: 'important' });
 *
 *   // remove default highlight
 *   $('#content').unhighlight();
 *
 *   // remove custom highlight
 *   $('#content').unhighlight({ element: 'em', className: 'important' });
 *
 *
 * Copyright (c) 2009 Bartek Szopka
 *
 * Licensed under MIT license.
 *
 */

jQuery.extend({
    highlight: function (node, re, nodeName, className) {
        if (node.nodeType === 3) {
            var match = node.data.match(re);
            if (match) {
                var highlight = document.createElement(nodeName || 'span');
                highlight.className = className || 'highlight';
                var wordNode = node.splitText(match.index);
                wordNode.splitText(match[0].length);
                var wordClone = wordNode.cloneNode(true);
                highlight.appendChild(wordClone);
                wordNode.parentNode.replaceChild(highlight, wordNode);
                return 1; //skip added node in parent
            }
        } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
            for (var i = 0; i < node.childNodes.length; i++) {
                i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
            }
        }
        return 0;
    }
});

jQuery.fn.unhighlight = function (options) {
    var settings = { className: 'highlight', element: 'span' };
    jQuery.extend(settings, options);

    return this.find(settings.element + "." + settings.className).each(function () {
        var parent = this.parentNode;
        parent.replaceChild(this.firstChild, this);
        parent.normalize();
    }).end();
};

jQuery.fn.highlight = function (words, options) {
    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
    jQuery.extend(settings, options);
    
    if (words.constructor === String) {
        words = [words];
    }
    words = jQuery.grep(words, function(word, i){
      return word != '';
    });
    words = jQuery.map(words, function(word, i) {
      return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    });
    if (words.length == 0) { return this; };

    var flag = settings.caseSensitive ? "" : "i";
    var pattern = "(" + words.join("|") + ")";
    if (settings.wordsOnly) {
        pattern = "\\b" + pattern + "\\b";
    }
    var re = new RegExp(pattern, flag);
    
    return this.each(function () {
        jQuery.highlight(this, re, settings.element, settings.className);
    });
};
function hiliter(word, element) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span class="myClass">' + word + '</span>';
    element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
hiliter('dolor');

자체 제작 강조 기능을 사용하는 것이 좋지 않은 이유

처음부터 자신만의 강조 기능을 구축하는 것이 좋지 않은 이유는 다른 사람들이 이미 해결한 문제에 부딪힐 것이 분명하기 때문입니다.과제:

  • DOM 않고 항목을 표시하려면 : DOM 이를트 파예로 지하으않고을일거리치적항강있텍요노제경이목합거해야우니다트를스드는을조표가소면:▁e▁you▁▁the▁).innerHTML)
  • 강조 표시된 요소를 제거하려면 HTML 요소를 해당 내용과 함께 제거하고 추가 검색을 위해 분할된 텍스트 노드를 결합해야 합니다.이것은 모든 형광펜 플러그인이 텍스트 노드 내에서 일치하는 항목을 검색하고 키워드가 여러 텍스트 노드로 분할되면 해당 키워드를 찾을 수 없기 때문에 필요합니다.
  • 또한 플러그인이 생각하지 못한 상황에서 작동하는지 확인하기 위한 테스트를 작성해야 합니다.그리고 저는 크로스 브라우저 테스트에 대해 말하고 있습니다!

복잡해요?일부 요소를 강조 표시에서 무시하는 기능, 분음 부호 매핑, 동의어 매핑, iframe 내부 검색, 분리된 단어 검색 등을 원한다면 이는 점점 더 복잡해집니다.

기존 플러그인 사용

잘 구현된 기존 플러그인을 사용할 경우 위의 명명된 사항에 대해 걱정할 필요가 없습니다.사이트포인트의 10jQuery 텍스트 형광펜 플러그인 기사는 일반적인 형광펜 플러그인을 비교합니다.여기에는 이 질문의 답변 플러그인이 포함됩니다.

mark.js를 보세요.

mark.js는 순수 JavaScript로 작성된 플러그인이지만 jQuery 플러그인으로도 사용할 수 있습니다.다른 플러그인보다 더 많은 기회를 제공하도록 개발되었으며 다음과 같은 옵션이 있습니다.

  • 전체 용어 대신 키워드를 별도로 검색
  • 지도 분음 부호(예: "justo"도 "just"와 일치해야 하는 경우)
  • 사용자 지정 요소 내부의 일치 항목 무시
  • 사용자 지정 강조 요소 사용
  • 사용자 지정 강조 클래스 사용
  • 사용자 정의 동의어 매핑
  • iframe 내부 검색
  • 조건을 찾을 수 없습니다.

데모

또는 이 바이올린을 볼 수 있습니다.

사용 예:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

GitHub(프로젝트 참조)에서 무료로 개발된 오픈 소스입니다.

다음은 사례를 무시하고 보존하는 변형입니다.

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp("\\b"+str+"\\b", "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};

제이에스아이들

사용하다.each(),.replace(),.html()jQuery 1.11 및 3.2로 테스트되었습니다.

위의 예에서 강조 표시할 '키워드'를 읽고 '강조 표시' 클래스와 함께 범위 태그를 추가합니다.'키워드' 텍스트는 에서 선택한 모든 클래스에 대해 강조 표시됩니다..each().

HTML

<body>
   <label name="lblKeyword" id="lblKeyword" class="highlight">keyword</label>
   <p class="filename">keyword</p>
   <p class="content">keyword</p>
   <p class="system"><i>keyword</i></p>
</body>

제이에스

$(document).ready(function() {
   var keyWord = $("#lblKeyword").text(); 
   var replaceD = "<span class='highlight'>" + keyWord + "</span>";
   $(".system, .filename, .content").each(function() {
      var text = $(this).text();
      text = text.replace(keyWord, replaceD);
      $(this).html(text);
   });
});

CSS

.highlight {
    background-color: yellow;
}

정규식에서도 작동할 수 있는 내 하이라이트 플러그인 jQuiteLight를 사용할 수 있습니다.

npm을 사용하여 설치하려면 다음을 입력합니다.

npm install jquitelight --save

샤워기 유형을 사용하여 설치하는 방법:

bower install jquitelight 

용도:

// for strings
$(".element").mark("query here");
// for RegExp
$(".element").mark(new RegExp(/query h[a-z]+/));

여기에서 고급 사용

다음 기능을 사용하여 텍스트의 모든 단어를 강조 표시할 수 있습니다.

function color_word(text_id, word, color) {
    words = $('#' + text_id).text().split(' ');
    words = words.map(function(item) { return item == word ? "<span style='color: " + color + "'>" + word + '</span>' : item });
    new_words = words.join(' ');
    $('#' + text_id).html(new_words);
    }

텍스트가 포함된 요소를 대상으로 지정하고 색상을 지정할 단어선택한 색상을 선택합니다.

다음은 예입니다.

<div id='my_words'>
This is some text to show that it is possible to color a specific word inside a body of text. The idea is to convert the text into an array using the split function, then iterate over each word until the word of interest is identified. Once found, the word of interest can be colored by replacing that element with a span around the word. Finally, replacing the text with jQuery's html() function will produce the desired result.
</div>

사용량,

color_word('my_words', 'possible', 'hotpink')

enter image description here

당신은 p 태그의 내용을 가져와 그 안의 모든 도어를 강조 표시된 버전으로 교체해야 합니다.

이를 위해 jQuery가 필요하지도 않습니다. :-)

저는 jQuery를 사용하여 각 키워드를 .highlight 클래스로 묶는 요소를 반복하는 매우 간단한 함수를 작성했습니다.

function highlight_words(word, element) {
    if(word) {
        var textNodes;
        word = word.replace(/\W/g, '');
        var str = word.split(" ");
        $(str).each(function() {
            var term = this;
            var textNodes = $(element).contents().filter(function() { return this.nodeType === 3 });
            textNodes.each(function() {
              var content = $(this).text();
              var regex = new RegExp(term, "gi");
              content = content.replace(regex, '<span class="highlight">' + term + '</span>');
              $(this).replaceWith(content);
            });
        });
    }
}

추가 정보:

http://www.hawkee.com/snippet/9854/

이것은 @bjarlestam에서 수정된 버전입니다.

텍스트만 검색합니다.

jQuery.fn.highlight = function(str) {
  var regex = new RegExp(str, "gi");
  return this.each(function() {
    this.innerHTML = this.innerText.replace(regex, function(matched) {
      return "<span class='mark'>" + matched + "</span>";
    });
  });
};

// Mark
jQuery('table tr td').highlight('desh')
.mark {
  background: #fde293;
  color: #222;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Sodeshi</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>Bangladesh</td>
  </tr>

</table>

용도:jQuery('.selector').highlight('sample text')

나는 html5에 의해 색상이 인식되는 텍스트의 색상을 변경하는 유사한 개념의 저장소를 만들었습니다(실제 #rgbb 값을 사용할 필요가 없으며 약 140개의 html5 표준화된 이름으로 사용할 수 있습니다).

colors.js colors.js

$( document ).ready(function() {
	
	function hiliter(word, element) {
		var rgxp = new RegExp("\\b" + word + "\\b" , 'gi'); // g modifier for global and i for case insensitive 
		var repl = '<span class="myClass">' + word + '</span>';
		element.innerHTML = element.innerHTML.replace(rgxp, repl);
			
			};

	hiliter('dolor', document.getElementById('dolor'));
});
.myClass{

background-color:red;
}
<!DOCTYPE html>
<html>
	<head>
		<title>highlight</title>
		
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	
		 <link href="main.css" type="text/css"  rel="stylesheet"/>
		 
	</head>
	<body id='dolor'>
<p >
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>
 <script type="text/javascript" src="main.js" charset="utf-8"></script>
	</body>
</html>

위의 예를 얻을 수 있습니까?

jQuery.fn.highlight = function (str, className)
{
    var regex = new RegExp(str, "g");

    return this.each(function ()
    {
        this.innerHTML = this.innerHTML.replace(
            regex,
            "<span class=\"" + className + "\">" + str + "</span>"
        );
    });
};

html-dll 내부의 텍스트를 대체하지 않습니다. 그렇지 않으면 페이지가 깨집니다.

$(function () {
    $("#txtSearch").keyup(function (event) {
        var txt = $("#txtSearch").val()
        if (txt.length > 3) {
            $("span.hilightable").each(function (i, v) {
                v.innerHTML = v.innerText.replace(txt, "<hilight>" + txt + "</hilight>");
            });

        }
    });
});

여기서 지피들

언급URL : https://stackoverflow.com/questions/119441/highlight-a-word-with-jquery

반응형