我正在尝试根据文本类型的输入和突出显示文本进行简单的jQuery单词搜索。如何为多个单词执行此操作?此代码仅适用于单个字符。
HTML
<input type="text"/>
<div>John Resig
George Martin
Malcom John Sinclair
J. Ohn
Sample text
</div>
CSS
span {
background : red
}
JS
$("input").keyup(function() {
var mysearchword = $("input:text").val();
var word = mysearchword;
$( "div:contains('"+word+"')" ).html(function(i,html) {
var re = new RegExp(word,"g");
return html.replace(re,'<span>'+word+'</span>')
});
});
答案 0 :(得分:10)
如果您有一组预定义的元素,那么
var $para = $('.para')
$("input").keyup(function() {
$para.find('span.highlight').contents().unwrap();
var mysearchword = this.value.trim();
if (mysearchword) {
var re = new RegExp('(' + mysearchword.trim().split(/\s+/).join('|') + ')', "gi");
$para.html(function(i, html) {
return html.replace(re, '<span class="highlight">$1</span>')
});
}
});
&#13;
span.highlight {
background: red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<div class="para">John Resig George Martin Malcom John Sinclair J. Ohn Sample text</div>
&#13;
答案 1 :(得分:0)
我已经修改了一些代码,并且能够实现您的需求。我不确定表现。
<强> HTML 强>
<input type="text" id="inputText" />
<div id="sampleText">
John Resig George Martin Malcom John Sinclair J. Ohn Sample text
</div>
<强> JS 强>
$("input").keyup(function () {
var mysearchword = $(this).val();
var word = mysearchword;
var textInDiv = $("#sampleText").text();
if (textInDiv.indexOf(word) > 0) {
var re = new RegExp(word, "g");
$("#sampleText").html(textInDiv.replace(re, '<span>' + word +'</span>'));
};
});