Using arrays to change color of certain words in an input box

后端 未结 5 739
温柔的废话
温柔的废话 2021-01-21 18:40

So I\'m working on a JSFiddle and I\'m a little confused about something. I have an input box called myTextField with a random paragraph and a button that calls my change functi

5条回答
  •  不知归路
    2021-01-21 19:31

    I think you want something like this:

    change = function() {
      var matches = ["every", "most", "that", "half", "much", "the", "another", "her", "my", "their", "a", "an", "his", "neither", "these", "all",
        "its", "no", "this", "any", "those", "both", "least", "our",
        "what", "each", "less", "several", "which", "either", "many", "some",
        "whose", "enough", "more", "such", "your"
      ];
    
      // get the current value of the "myTextField" element
      var myTextFieldValue = document.getElementById('myTextField').value;
    
      // split this string at every space character - we now have
      // an array of individual words
      var myTextFieldWords = myTextFieldValue.split(' ');
    
      // for each of these words, test if the "matches" array contains
      // the word.  If it does, surround it with a  tag.
      var formattedWords = myTextFieldWords.map(function(word) {
        if (matches.indexOf(word) !== -1) {
          return '' + word + '';
        } else {
          return word;
        }
      });
    
      // formattedWords now looks like this:
      // ['his', 'first' 'entering', 'a' .... ]
      
      // join all the items in the formattedWords array (with a 
      // space between each word) into a single string, and set
      // it as the innerHTML of the #title element
      document.getElementById('title').innerHTML = formattedWords.join(' ');
    }
    .match {
      color: blue;
    }
    
    
    

提交回复
热议问题