HTML
<input type="text" id="#searchfor">
<p id="all_text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</p>
代码
$('#searchfor').keyup(function(){
var page = $('#all_text');
var pageText = page.text().replace("<span>","").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("("+searchedText+")", "igm");
var newHtml = pageText.replace(theRegEx ,"<span>$1</span>");
page.html(newHtml);
});
嗨, 这解决了一个问题。如果我寻找LOREM,然后将其删除,则会发生这种情况
TEXT
<span></span>L<span></span>o<span></span>r<span></span>e<span></span>m<span></span> ipsum
原始jsFiddle。它工作正常,但是如果搜索为空,我想删除所有 span ,但是我不知道该怎么做。有人能帮我吗?谢谢!
答案 0 :(得分:1)
您可以将所有文本存储到临时变量中,并在搜索框值为空时使用它: 这是一个例子。
//here we will store the original text only first time
var originalText ="";
$('#searchfor').keyup(function(){
var page = $('#all_text');
//storing the original text into variable
if(originalText ===""){
originalText = page.text();
}
var pageText = page.text().replace("<span>","").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("("+searchedText+")", "igm");
var newHtml = pageText.replace(theRegEx ,"<span>$1</span>");
page.html(newHtml);
//replacing html if textbox has been cleared
if($(this).val() === ''){
page.html(originalText);
}
});
#all_text span
{
text-decoration:underline;
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchfor"/>
<p id="all_text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</p>