我正在尝试使用javascript来替换带有样式字符的段落中的字符。如果我用一种样式替换一个字符它可以正常工作,但是当我尝试用3种不同的样式替换3个不同的字符时,段落将被打印3次,每次只有1次样式更改。我希望3个样式在1段中生效。以下是我正在使用的代码。谢谢。
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction (){
var pText=document.getElementById("alteredText").innerHTML;
var eSpan=pText.replace(/e/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");
var tSpan=pText.replace(/t/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");
var sSpan=pText.replace(/s/g,"<span style='color:green;'>s</span>");
var n = eSpan.concat(tSpan,sSpan);
document.getElementById("alteredText").innerHTML=n;
}
</script>
</head>
<body onLoad="myFunction()">
<p id="alteredText">
The quick brown fox jumped over the lazy sleeping dog.
The slow shiny robot chased the quick brown fox.
The lazy sleeping dog awoke and barked at the slow shiny robot.
</p>
</body>
</html>
答案 0 :(得分:2)
var pText=document.getElementById("alteredText").innerHTML;
var t = pText.replace(/e/g,"@e@");
t = t.replace(/t/g,"@t@");
t = t.replace(/s/g,"@s@");
t = t.replace(/@e@/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");
t = t.replace(/@t@/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");
t = t.replace(/@s@/g,"<span style='color:green;'>s</span>");
document.getElementById("alteredText").innerHTML=t;
答案 1 :(得分:0)
试试这个:
var first = pText.replace(/e/g,"<span style='position:relative;color:red;top:.05em;'>e</span>");
var second = first.replace(/t/g,"<span style='position:relative;color:blue;top:-.05em;'>t</span>");
var final = second.replace(/s/g,"<span style='color:green;'>s</span>");
document.getElementById("alteredText").innerHTML=final;
看看我做了什么?您正在创建三个字符串,每个字符串都有一个替换。在这里,我在已经包含第一个的字符串中进行第二次替换。在最后一次替换之后,我把它放在元素中。
答案 2 :(得分:0)
一个快速和肮脏的解决方案:
function myFunction (){
var pText=document.getElementById("alteredText").innerHTML;
var eSpan=pText.replace(/e/g,"<SPAN STYLE='POSITION:RELATIVE;COLOR:RED;TOP:.05EM;'>e</SPAN>"); // CAPS are needed so no match is found in the next replace
var tSpan=eSpan.replace(/t/g,"<SPAN STYLE='POSITION:RELATIVE;COLOR:BLUE;TOP:-.05EM;'>t</SPAN>");
var sSpan=tSpan.replace(/s/g,"<SPAN STYLE='COLOR:GREEN;'>s</SPAN>");
// var n = eSpan.concat(tSpan,sSpan); //<-- this creates the three copies of the paragraph. you don't need this.
document.getElementById("alteredText").innerHTML=sSpan;
}