Javascript:搜索和突出显示包含HTML标记

时间:2013-12-16 07:52:32

标签: javascript jquery html

所以我正在编写这样的代码,当用户在文本框中搜索查询时,它会在内容的某处突出显示查询,并关注该查询的第一次出现。问题是,当用户键入HTML标记的 li div 之类的内容时,这些内容也会显示为搜索结果。例如,这是我的html标记

<div class="col-lg-6" id="search-area">
    <div class="input-group">
      <input type="text" id="search-term" class="form-control">
      <span class="input-group-btn">
        <button id="search-button" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
      </span>
    </div><!-- /input-group -->
</div>

<h3>Did we miss something? Have any more FAQs to add? Contact us directly at blabla@gmail.com</h3>

这是我的js

    function searchAndHighlight(searchTerm, selector) {
if(searchTerm) {

    var selector = selector || "#mainContainer"; 
    var searchTermRegEx = new RegExp(searchTerm,"ig");
    var matches = $(selector).text().match(searchTermRegEx);
    if(matches) {
        $('.highlighted').removeClass('highlighted');     //Remove old search highlights
            $(selector).html($(selector).html()
                .replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));
        if($('.highlighted:first').length) {             //if match found, scroll to where the first one appears
            $(window).scrollTop($('.highlighted:first').position().top);


        }
        return true; 

    }
    }

    return false;


    }

    $(document).ready(function() {
    $('#search-button').on("click",function() {
    if(!searchAndHighlight($('#search-term').val())) {
        alert('No results found for query "'+$('#search-term').val()+'".');
    }else{
        alert($("span[class='highlighted']").length);
    }
    });

    $("#search-term").keypress(function(event) {
    if (event.which == 13) {
        if(!searchAndHighlight($('#search-term').val())) {
            alert('No results found for query "'+$('#search-term').val()+'".');
        }else{
            alert($("span[class='highlighted']").length);
        }
    }
    });


    });

如果用户输入 h3 ,结果将是

<**h3**>Did we miss something? Have any more FAQs to add? Contact us directly at blabla@gmail.com</**h3**>

不应该说没有找到结果吗?

1 个答案:

答案 0 :(得分:0)

尝试更改代码以迭代所有子节点并检查它们的值()而不是它们的html():

....
  var selector = selector || "#mainContainer"; 
    var searchTermRegEx = new RegExp(searchTerm,"ig");
    var matches = [];

    $.each($(selector).children(), function(index, item){
        matches.push($(item).val().match(searchTermRegEx));
    });

    if(matches) {....