我正在尝试基于类型文本的输入和突出显示文本进行简单的jQuery单词搜索.我怎么能这样做多个单词?此代码仅适用于单个字符.
<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>') }); });
解决方法
如果您有一组预定义的元素来定位
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>') }); } });
span.highlight { background: red }
<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>