简体   繁体   English

jQuery插件-突出显示文本

[英]jQuery plugin - highlight text

I'm creating a jQuery plugin. 我正在创建一个jQuery插件。 It takes user input and should highlight the text in the existing page content. 它需要用户输入,并应突出显示现有页面内容中的文本。 Right now, the plugin is highlighting the entire line which includes the content entered by the user. 现在,该插件将突出显示包括用户输入内容在内的整个行。

Ideally it only matches the entered phrase. 理想情况下,它仅与输入的短语匹配。

I have three files: 我有三个文件:

HTML FILE : HTML文件:

<input type="text" id="name">
<p>harry gambhir is sitting in oakville tim hortons drinking coffe </p>

PLUGIN FILE : 插件文件:

$(document).ready(function(){
(function ( $ ) {
$.fn.high = function(){
    $("#name").keyup(function(){
        var user = $(this).val();
        var hhh = $("p:contains('"+ user + "')").addClass('highlight');

    });
};
}(jQuery));
$('p').high();
});

CSS FILE: CSS文件:

.highlight{

    background-color:#000000;

}

Maybe I need to create a span tag around the alphabet then add the class to highlight it. 也许我需要围绕字母创建一个span标签,然后添加该类以使其突出显示。 I do not know how to assign a span tag to the entered text. 我不知道如何将span标签分配给输入的文本。 This is just an idea if there is a better solution then please let me know. 这只是一个想法,如果有更好的解决方案,请告诉我。

Try using .html() , .text() , String.prototype.replace() , saving original html of p element as variable to reset p element html if .val() returns empty string 尝试使用.html() .text() String.prototype.replace()保存原始htmlp元素作为变量重置p元件html如果.val()返回空字符串

 $(document).ready(function() { (function($) { // pass element selector to `.high()` $.fn.high = function(elem) { // cache `this` element el = this; // save original `html` of `el` originalHTML = el.html(); $(elem).keyup(function() { var user = $(this).val(); // if `user` is not empty string if (user.length) { el.html(function(_, html) { return el.text() .replace(new RegExp("(" + user.trim().split("").join("|") + ")" , "g") // replace matched character with `span` element // add `highlight` `class` to `span` element , "<span class=highlight>$1</span>") }) } else { // reset `p` : `el` `html` to `originalHTML` el.html(originalHTML) } }); }; }(jQuery)); $("p").high("#name"); // pass `#name` as selector to `.high()` }); 
 .highlight { color: yellow; background-color: #000000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <input type="text" id="name"> <p>harry gambhir is sitting in oakville tim hortons drinking coffe</p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM