通过搜索查找下一个文本并突出显示无效

时间:2016-09-26 14:55:24

标签: javascript jquery html regex search

在搜索框中搜索任何文本时,可以找到并突出显示正确的文本,但是当搜索下一个/新文本时,它无法找到下一个/新文本,再次搜索时它无法正常工作,我无法找到问题。下面的 JS

JS

$('button#search').click(function() {
 var page = $('#ray-all_text');
   var pageText = page.html().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);
  $('html, body').animate({
  scrollTop: $("#ray-all_text span").offset().top }, 2000);
});

HTML

<div class="ray-search">
  <div class="field" id="ray-search-form">
    <input type="text" id="searchfor" placeholder="what are you searching for?" />
    <button type="button" id="search">Press to Find!</button>
  </div>
</div>

<article id="ray-all_text">
  <p>
    This manual and web site, all information and data and photos contained herein, are the s...
  </p>
</article>

请查看实时示例:https://jsfiddle.net/gaezs6s8
为什么会这样?有解决方案吗?

1 个答案:

答案 0 :(得分:1)

我的建议是在更改要避免意外行为的文本中的所有.html()之前进行一些验证并改进功能。

首先进行验证以避免“空间”。作为输入的第一个值,这将让我们稍后检查输入内部是否具有实际值。

$('body').on('keydown', '#searchfor', function(e) {
    if (e.which === 32 &&  e.target.selectionStart === 0) {
      return false;
    }  
});

Code from this answer

现在请检查您的代码的评论:

//Create some vars to later check for: 
//['text you are searching', 'number of highlights','actual highlight']
var searching,
    limitsearch,
    countsearch;

$('button#search').click(function() {
    var searchedText = $('#searchfor').val();
    var page = $('#ray-all_text');

    //Now check if the text on input is valid
    if (searchedText != "") {
        //If the actual text on the input is different from the prev search
        if(searching != searchedText) {
            page.find('span').contents().unwrap();
            var pageText = page.html();
            var theRegEx = new RegExp("(" + searchedText + ")", "igm");
            var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
            page.html(newHtml);
            //Set your variables to the actual search
            searching = searchedText;
            limitsearch = page.find('span').length;
            countsearch=0;
        } else {
            //If it's the same of the prev search then move to next item instead of repaint html
            countsearch<limitsearch-1 ? countsearch++ : countsearch=0;
            console.log(countsearch+'---'+limitsearch)
        }
        //Go to target search
        $('body').animate({
          scrollTop: $("#ray-all_text span").eq(countsearch).offset().top - 50}, 
        200);
     } else {
        alert('empty search')
     }
});

JqueryDemo