【问题标题】:How to search page for words and highlight them (JQuery)如何在页面中搜索单词并突出显示它们(JQuery)
【发布时间】:2018-10-23 00:17:13
【问题描述】:

我目前有一个用户输入的单词数组和存储在对象中的相应突出显示颜色(以下是在用户按钮单击和输入时构造数组的函数):

//DECLERATIONS////
var placementId = 0;
var searchList = [];

///FUNCTION THAT ADDS A NEW WORD TO SEARCHLIST////////
function addWord(userWord, userColor){ //append new word to find and highlight
    var wordAndColorPair = {
        word: userWord,
        color: userColor,
        id: placementId
    }
    searchList.push(wordAndColorPair);
}

///////BELOW IS THE EVENT THAT ACTUALLY CONSTRUCTS THE ARRAY//////////

$('.color-element').click(function(){ //adding new word-color pairs
    var userInput = $('#input-word').val();
    if(userInput !== ''){ //only if user enteres text:
        var newWord = document.createElement("span"); //create a new search word tile

        newWord.classList.add('search-word'); //add the class search-word to it
        newWord.textContent = userInput; //make its text value equal to the input

        var colorId = $(this).attr('id'); //set its bacckground color to a copy of the button clicked
        $(newWord).css("background-color", colorId);

        $(newWord).attr('id', placementId); //set this new elements unique ID for delection purposes

        $('.display-array').append(newWord); //append the child to the DOM

        addWord(userInput, colorId, placementId); //add the word to the search list - increment placementId for future words
        placementId ++;

        $('#input-word').val(''); //reset the input field
    }
    else{
        return;
    }
});

我遇到的问题是能够搜索整个页面并实际突出显示数组中看到的单词。到目前为止我所拥有的是:

$('.search').click(function(){ //when the search button is clicked
    var i;
    for(i =0; i< searchList.length; i++){//for each word user inputted:
        $("*").contents().each(function() {
            var word = searchList[i].word;
            var regex = new RegExp('(\\b'+word+'\\b)', 'gi');
            if(this.nodeType == 3){ //if text
                $(this).html(text.replace(regex, " <span style = 'background-color: " + searchList[i].color + " ;'> " + searchList[i].word + "</span>"));
            }
        });
    }
});

但是,这似乎不起作用,非常感谢任何帮助!

用于 DOM 参考的 HTML:

<html lang="en">

<head>
    <link href="https://fonts.googleapis.com/css?family=Changa:700|Roboto+Condensed:700" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">

    <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script type = "text/javascript" src="popup.js"></script>
    <meta charset="utf-8">
    <title>Word Finder</title>
    <link rel="stylesheet" href="style.css" media="screen">

    <meta name="description" content="Word Finder Chrome Extension">
    <meta name="author" content="Aalok Borkar">
</head>

<body>
    <p>
        this is a test of the funcitonality TEXT text text text hello

    </p>

    <div class = "input">
        <div class = "word">
            Word <input type = "text" id = 'input-word' placeholder= "Jim Halpert"></input>
        </div>

        <div class = "color-palette">
            <!-- on click: clear text input, add color, append search array / display array -->
            <button class = "color-element" id = "red"></button>
            <button class = "color-element" id = "orange"></button>
            <button class = "color-element" id = "yellow"></button>
            <button class = "color-element" id = "green"></button>
            <button class = "color-element" id = "blue"></button>
            <button class = "color-element" id = "violet"></button>
            <button class = "color-element" id = "pink"></button>               
        </div>
    </div>

    <div class = "display">
        <p> Words to Search</p>
        <div class = "display-array">
        </div>
    </div>

    <button class = "search">Search</button>

</body>

</html>

【问题讨论】:

  • 我们没有看到 dom 树的样本?
  • 我添加了 HTML 代码
  • 在后一个函数中,文本将是例如$('#input-word').val() ?
  • 是的,这就是您访问用户输入的方式?

标签: javascript jquery nodes highlight


【解决方案1】:

我向您的&lt;p&gt; 元素添加了一个类,但您可能不必这样做。我这样做只是为了方便我访问。如果我理解你的问题,最重要的是你的搜索功能。 IMO,您需要查看每个单词并将其与搜索数组进行比较。找到匹配的单词并将其包装在您可以应用样式的内容中。就我而言,我选择了&lt;span&gt; 标签。摆弄下面的代码。

// HTML Modification
<p class="searchable">
  this is a test of the functionality TEXT text text text hello
</p>

$('.search').click(function() { //when the search button is clicked
  var original = $('.searchable').html().trim();
  var searchable = original.split(" ");
  for (var i = 0; i < searchList.length; i++) { //for each word user 
inputted:
    for (var s = 0; s < searchable.length; s++) {
      if (searchable[s] == searchList[i].word) {
        searchable[s] = "<span style='background:" + searchList[i].color + 
";'>" + searchList[i].word + "</span>";
      }
    }
  }

  rewrite(searchable);  //SEE BELOW
});

// This iterates over the searchable array
function rewrite(searchable) {
  var highlighted = "";
  for (var i = 0; i < searchable.length; i++) {
    highlighted += searchable[i] + "&nbsp;";
  } 
  $('.searchable').html(highlighted.trim());
}

https://jsfiddle.net/5v3aqrzd/

【讨论】:

    【解决方案2】:

    需要这样做:

    $(this).parent().html($(this).parent().html().replace($(this).text(),$(this).text().replace(regex, " <span style = 'background-color: " + searchList[i].color + " ;'>" + searchList[i].word + "</span> ")));
    

    这是因为当您直接更改 innerHTML 时,您会弄乱 dom 结构并丢失 html 格式,当您仅更改文本时,您将在引号内有一个经过消毒的 DOM,因此应该通过修改一种方法来解决内部 html 中的文本部分。

    see it here

    【讨论】:

    • 是否有更简单的方法可以做到这一点,因为我对您提供的答案感到非常困惑
    • 在下面查看我的答案。
    猜你喜欢
    • 2013-09-15
    • 1970-01-01
    • 2015-10-14
    • 2011-12-20
    • 2012-04-18
    • 2014-02-15
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多