display and color part of a string using span

时间:2015-07-28 22:16:12

标签: javascript html

I am trying to do a text replace and highlight using javascript.

.replace(/sentence_old/g, '"Is \'verbexample1\' the \'verbsenseexample1\' in this sentence?"');

In this case, verbexample1 and verbsenseexample1 are going to be read in from a JSON file. The above code already successfully displays the pseudo string above. I need a way to display the sentence and highlight the "verbexample1" and "verbsenseexample1" with different colors using <span>. Can anyone help me with the syntax? I have tried the example below but I am getting an SyntaxError: Unexpected identifier error.

'"Is '<span style="color: #FFFF00">'+obj[0].srcLanguageSentence.text+'</span>'+the+"'<span style="color: #FFFF00">'+obj[1].srcLanguageSentence.text+'</span>' in this sentence?"');

2 个答案:

答案 0 :(得分:0)

what exactly have you tried with using span?

you can probably do something like this:

.replace(/sentence_old/g, '\x22Is <span id=\x22span1\x22>\x27verbexample1\x27</span> the <span id=\x22span2\x22>\x27verbsenseexample1\x27</span> in this sentence?\x22');

and the following css:

#span1 { 
        color: red;}
#span2 {
        color: green;}

答案 1 :(得分:0)

这还不够完整,但无论如何都会提出答案。

使用obj[0].srcLanguageSentence.innerHTML而不是obj[0].srcLanguageSentence.text,因为我怀疑你想要在对象中使用HTML - 但由于没有其他代码,我们无法分辨对象obj的类型,或者你是似乎很可能操纵DOM。 innerHTML的来源:http://www.w3schools.com/jsref/prop_html_innerhtml.asp

您还需要包含声明此元素的位置,并在声明元素后检查您的javascript运行如果这不起作用,即<head>中没有脚本。