更改句子中与单词中的单词匹配的单词的颜色

时间:2016-07-12 19:49:19

标签: javascript arrays colors

试图找出如何编码 - 希望有人可以提供帮助!

我正在创建一个简单的项目,允许用户通过单击按钮更改特定单词的颜色。

例如,这是句子:

<p>i cant believe mary tried to kill her own sister, bella ! </p>

我要改变颜色的词是“mary”,“kill”,“bella”

我知道我需要有一个我想改变的单词数组,但我不知道如何用数组分配/连接句子。

我已经编码了一个改变整个句子颜色的按钮*但是无法想出如何连接数组元素 - 有谁知道怎么做?谢谢!

*代码

 <p>i cant believe mary tried to kill her own sister, bella !</p> 
 <br/>

 <input id="changeColor" type="button" value="Change Color" />

//JQUERY CHANGES TEXT TO BLUE WHEN BUTTON IS CLICKED
$(function() {
    $('#changeColor').click( function() {
        $("p").css({"color":"blue"});
    });
});
  

编辑:审核了您们留下的评论 - 抱歉遗漏重要信息!感谢您的反馈!

4 个答案:

答案 0 :(得分:1)

const words = ['mary', 'kill', 'bella']

const p = document.querySelector('p')
var newHTML = p.innerHTML
words.forEach(word=>
  newHTML = newHTML.replace(word, `<span class="color">${word}</span>`)
)
p.innerHTML = newHTML
.color {
  color: red;
}
<p>i cant believe mary tried to kill her own sister, bella ! </p>

首先,将要更改颜色的单词放在数组中。然后使用<p>选择document.querySelector()元素。将该元素的当前HTML内容分配给变量,对于数组中的每个单词,将该世界替换为包含该单词的<span>color。然后将更改的HTML分配给innerHTML元素的<p>属性。

您还必须在CSS中设置所需的颜色。

答案 1 :(得分:0)

如果您只是制作一个“允许用户通过点击按钮更改特定单词颜色的简单项目”,那么您只需在每个单词中添加<span>标记即可。通过定位每个ID如下所示在javascript中更改它们。你说“我知道我需要一个数组”但我不知道你是否意味着你认为你只能用数组做这个或者你想用数组做这个。对我来说,它听起来像前者,所以下面没有使用数组和span标签。如果您需要使用数组执行此操作,则可以使用非常类似的方式完成此操作,但如果您需要3个单独的按钮,则不一定非必要。

function changeRed() {
 document.getElementById('red').style.color = 'red';
  }

function changeBlue() {
 document.getElementById('blue').style.color = 'blue';
  }

function changeGreen() {
 document.getElementById('green').style.color = 'green';
  }
 
<p>i cant believe <span id="red">mary</span> tried to <span id="blue">kill</span> her own sister, <span id="green">bella</span> ! </p>

<button type="button" onclick="changeRed()">mary</button>
<button type="button" onclick="changeBlue()">kill</button>
<button type="button" onclick="changeGreen()">bella</button>

答案 2 :(得分:0)

您可以在单词周围添加jasmine_nodejs: { // task specific (default) options options: { specNameSuffix: ["-spec.js"], // also accepts an array helperNameSuffix: "helper.js", useHelpers: false, stopOnFailure: false, reporters: { console: { colors: true, cleanStack: 1, // (0|false)|(1|true)|2|3 verbosity: 4, // (0|false)|1|2|3|(4|true) listStyle: "indent", // "flat"|"indent" activity: false }, junit: { savePath: "./test-reports", filePrefix: "testresult", consolidate: true, useDotNotation: true } } }, test: { // target specific options options: { useHelpers: false }, // spec files specs: [ "test/*", ] } }, 标记,并为其指定spanid=mary等。

如果您希望所有这些单词更改为相同的颜色,只需为每个id=kill指定相同的类名。

您能包含目前编写的代码吗?

答案 3 :(得分:0)

我在下面的代码评论中对此进行了解释。

HTML:

<div id="sentenceContainer">Placeholder</div>
<button id="changeButton">Change</button>
<button id="resetButton">Reset</button>

CSS:

#sentenceContainer {
  position: relative;
  color: white;
  background-color: black;
  height: 40px;
  line-height: 40px;
}

#sentenceContainer > span:not(:first-child) {
  padding-left: 5px;
}

.red {
  color: red;
}

JavaScript的:

// We make an array of the words
var words = ["i", "cant", "believe", "mary", "tried", "to", "kill", "her", "own", "sister,", "bella", "!"];

// These are the indices from the array above that correspond to the words you want to turn red
var redIndices = [3, 6, 10];

$('#changeButton,#resetButton').on('click', writeWords);

// This is the function that will write the sentence for us
function writeWords(evt) {

  // Get the ID of the target to know if we are changing or resetting
  var red = evt && evt.target && $(evt.target).attr('id') === 'changeButton' ? true : false;

  // This grabs our sentenceContainer
  // Always grab these outside of any loops to speed up code execution
  // Otherwise there would be a DOM traversal for each iteration of the loop
  var sentenceContainer = $('#sentenceContainer');

  // Empty it so it doesn't repeat the sentence
  sentenceContainer.empty();

  // Iterate the words array
  for (var i = 0; i < words.length; i++) {

    // Generate the container
    var wordSpan = $('<span></span>');

    // Add the word to it
    wordSpan.text(words[i]);

    // If this is a word we want red, from redIndices - we add the class red
    if (red && redIndices.indexOf(i) >= 0)
      wordSpan.addClass('red');

    // Append the word container to the sentence container
    sentenceContainer.append(wordSpan);
  }

};

writeWords();

直播观看:

http://codepen.io/noahtkeller/pen/QEOOyL