更改JS中段落的一部分的文本颜色

时间:2018-06-23 21:53:20

标签: javascript html

我有一个JS函数来处理段落元素。我有一本字典。我需要用字典的每个键检查段落的每个单词,如果它们匹配,则需要通过单击按钮将原始段落单词涂成红色。

JS函数

function n()
{
var a = {German:["German1","German2"],plays:["plays1","plays2"],forward: 
["forward1","forward2"]};
var x = document.getElementById("p1").textContent.split(" ");

for (i=0; i<x.length; i++)
    {
        for (j=0; j<Object.keys(a).length; j++)
            {
                if (x[i]==Object.keys(a)[j])
                    {
                        x[i].style.color="red";
                    }
            }
    }
}

HTML

<p id="p1">Marco Reus is a German professional footballer who plays as a 
forward for Borussia Dortmund and 
the Germany national team. He is renowned for his versatility, speed and 
technique, 
but also for proneness to injury.</p>

<button name="b1" onclick="n()">Next</button>

但是在单击按钮后,控制台说无法将n的undefined属性'color'设置为n。我该如何解决?

1 个答案:

答案 0 :(得分:1)

正如我评论的那样,您不能使用style为单个单词着色,并且数组项不是DOM元素并且没有style属性,因此错误为{{1 }}。

一种可能的解决方案是将这些单词替换为自己,并以例如Cannot set property 'color' of undefined

在下面的代码段中,我简化了您的脚本,因为您不需要迭代span中的所有单词,只需迭代对象键,然后简单地替换找到的键即可。 < / p>

堆栈片段

p
function n() {
  var a = {
    German: ["German1", "German2"],
    plays: ["plays1", "plays2"],
    forward: ["forward1", "forward2"]
  };
  var p = document.getElementById("p1"),
      keys = Object.keys(a);

  for (j = 0; j < keys.length; j++) {
    p.innerHTML = p.innerHTML.replace( new RegExp("\\b"+keys[j]+"\\b","g"),"<span style='color:red'>" + keys[j] + "</span>")
  }
}