我有一个 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/