简体   繁体   English

使用Java脚本更改HTML标记中特定文本的颜色

[英]Change color of specific text within HTML tags using Javascript

The question says it all. 问题说明了一切。 For example I have the following HTML code: 例如,我有以下HTML代码:

<span id="span">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor<span>

How do I change the color of the color of any word from above without modifying the span above(I know I could have put another span tag with an id="text" and used document.getElementById("text").style.color="red"; . But instead of this I want to search for the word in the tag(maybe using RegExp) and change it's color dynamically. 如何在不修改上方span情况下从上方更改任何单词的颜色(我知道我可以在另一个span标签中添加id="text"并使用document.getElementById("text").style.color="red";但是,我想代替它在标记中搜索单词(也许使用RegExp)并动态更改其颜色。

You can't do it without modifying the contents of the span. 不修改跨度的内容就无法做到。 So you either do that in the source, or you do it later by manipulating the DOM (in your case, via jQuery). 因此,您可以在源代码中执行此操作,也可以稍后通过操作DOM(在您的情况下,通过jQuery)进行操作。

So for instance: 因此,例如:

 var span = $("#span"); span.html(span.html().replace(/dolor/, '<span style="color: red">$&</span>')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span id="span">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor</span> 

The $& in the replacement string is the word that was found. 替换字符串中的$&是找到的单词。 In the above, only the first occurrence would be replaced; 在上面,只有第一次出现会被替换; to replace multiple occurrences, add a g to the end of the regular expression ( /dolor/g ). 取代多次出现,一个添加g正则表达式(的端部/dolor/g )。

Note that if you have any event handlers attached to any elements within the span , they will get removed by this, as the contents of the span get removed and then replaced. 请注意,如果将任何事件处理程序附加到span内的任何元素,它们将被此删除,因为span的内容将被删除然后替换。 (As your example doesn't have any elements at all within the span , I figured that wouldn't be the case, but figured I should mention it.) (由于您的示例在span内根本没有任何元素,因此我认为情况并非如此,但我想提一下。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM