Как найти на странице слова и выделить их (JQuery) - PullRequest
0 голосов
/ 13 мая 2018

В настоящее время у меня есть массив введенных пользователем слов и соответствующих цветов подсветки, хранящихся в объектах (ниже приведена функция, которая создает массив при нажатии и вводе пользователем кнопки):

//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>"));
            }
        });
    }
});

Это, похоже, не работает, любая помощь очень ценится!

HTML для ссылки DOM:

<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>

Ответы [ 2 ]

0 голосов
/ 13 мая 2018

Я добавил класс к вашему <p> элементу, но вам, вероятно, не нужно этого делать. Я просто сделал это для облегчения доступа с моей стороны. Самым важным, если я правильно понял ваш вопрос, была ваша функция поиска. ИМО, вам нужно посмотреть каждое слово и сравнить его с поисковым массивом. Найдите подходящее слово и оберните его во что-нибудь, к чему вы можете применить стиль. В моем случае я выбрал тег <span>. Скрипка ниже кода.

// 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/

0 голосов
/ 13 мая 2018

Это нужно сделать следующим образом:

$(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.

см. здесь

...