如何根据行号实现循环

时间:2018-02-14 17:02:06

标签: javascript html loops for-loop while-loop

我需要为每一行更改某些单词的颜色 我有一个wordInput表,它的意思是包含我需要为它们着色的单词,第二个表包含我需要为它着色一些单词的标题。

我的脚本工作时行标题的数量等于数量     行wordInput和那是错的!因为有时我只有1     行作为输入。我需要找到如何做循环的解决方案     每一行标题我在需要时得到错误评估脚本     更改第二行标题的颜色

  

TypeError:无法调用null(#4)

的方法“split”

这个错误,因为现在我们在第二行输入词中,它没有值

var row = {
  "Title": ["This reference is to serve as a useful","Title2","Title3"],"wordInput":["serve"] }
//Title contains 3 rows : as string Values
//wordInput contains words that i need to color them in Title :As a string Value
var words = row["wordInput"];// this contain only 1 row ["serve"]
var orgTitle = row["Title"];

words.split(" ").forEach(function (word) {
  orgTitle = orgTitle.replace(new RegExp(word, "g"),'<span style="color: red;">'+word+'</span>');
});


orgTitle;

我正在寻找你的帮助,谢谢

1 个答案:

答案 0 :(得分:0)

假设row.title是包含应突出显示的所有单词的数组,这就是您所需要的。

&#13;
&#13;
var row = {
  "Abstract": "This reference is to serve as a useful reference for testing whether the styling of reference,  works or not. All        occurances of 'reference' should be given a color of red.",
  "Title":["reference" ,"testing"]
};


var wordsToHighlight = row['Title'];
var result = row["Abstract"];

wordsToHighlight.forEach(function (word) {
  result = result.replace(new RegExp(word, "g"),'<span style="color: red;">'+word+'</span>');
});
document.querySelector("#result").innerHTML = result;
&#13;
<div id="result">
</div>
&#13;
&#13;
&#13;