我正在创建一个 jQuery 插件。它接受用户输入,并应突出显示现有页面内容中的文本。现在,该插件会突出显示包含用户输入的内容的整行。
理想情况下,它只匹配输入的短语。
我有三个文件:
HTML 文件:
<input type="text" id="name">
<p>harry gambhir is sitting in oakville tim hortons drinking coffe </p>
插件文件:
$(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 文件:
.highlight{
background-color:#000000;
}
也许我需要围绕字母表创建一个 span 标签,然后添加类以突出显示它。我不知道如何为输入的文本分配 span 标签。这只是一个想法,如果有更好的解决方案,请告诉我。
最佳答案
尝试使用 .html()
, .text()
, String.prototype.replace()
,保存原始 html
作为变量重置 p
元素的 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>
关于javascript - jQuery 插件 - 高亮文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34971049/