javascript - JS改变部分段落的文字颜色

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

但是单击按钮后,控制台显示 Cannot set property 'color' of undefined at n.我该如何解决这个问题?

最佳答案

正如我所评论的,你不能使用 style 为单个单词着色。 ,并且数组项不是 DOM 元素,并且没有 style属性,因此出现错误 Cannot set property 'color' of undefined .

一种可能的解决方案是将这些单词替换为它们本身,例如包裹在一个span

在下面的代码片段中,我简化了您的脚本,因为您不需要迭代 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>")
  }
}
<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>

关于javascript - JS改变部分段落的文字颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51005351/

相关文章:

html - 纯 CSS 过渡动画字体颜色

html - 在特定位置放置带有悬停图像的圆圈

javascript - 将 as3 btn 代码转换为 Javascript

javascript - 没有得到我期望的计算结果

javascript - 递归获取第一个空选择框

javascript - 日期和时间选择器不起作用

HTML对象标签不继承CSS

php - Magento 中的 IWD Onepage Checkout getItemHtml 模板

javascript - 如何通过 jquery 调用使用 jquery 设置的选定选项 php 变量?

javascript - 滑动 slider ...删除箭头