繁体   English   中英

使用 JavaScript 更改文本内容后,如何仅加粗一个单词?

[英]How can I bold only one word, after I change the text content with JavaScript?

在通过 JavaScript 更改 HTML 中的文本内容后,我一直试图将单个单词加粗。

这是我的代码:

 document.getElementById('par3').textContent = "I <b>love</b> JS";
 <!DOCTYPE html> <html> <head> <title>Homework05</title> </head> <body> <p id="par1">Unchanged Paragraph</p> <p id="par2">Unchanged Paragraph</p> <p id="par3">Unchanged Paragraph</p> <p id="par4">Unchanged Paragraph</p> <p id="par5">Unchanged Paragraph</p> <script src="script.js"></script> </body> </html>

不知何故, 标签不呈现。 是否有任何特定的转义字符? 或者这是要完成的更复杂的事情?

你需要使用innerHTML textContent将转义您的字符串。

 document.getElementById('par3').innerHTML= "I <b>love</b> JS"; 
 <!DOCTYPE html> <html> <head> <title>Homework05</title> </head> <body> <p id="par1">Unchanged Paragraph</p> <p id="par2">Unchanged Paragraph</p> <p id="par3">Unchanged Paragraph</p> <p id="par4">Unchanged Paragraph</p> <p id="par5">Unchanged Paragraph</p> <script src="script.js"></script> </body> </html> 

use innerHTML other then textContent or

选择单词并将其定义为字符串var然后使用字符串 .bold()方法。

textContent将忽略字符串中的html标记。 使用innerHTML而不是textContent

 document.getElementById('par3').innerHTML = "I <b>love</b> JS"; 
 <p id="par1">Unchanged Paragraph</p> <p id="par2">Unchanged Paragraph</p> <p id="par3">Unchanged Paragraph</p> <p id="par4">Unchanged Paragraph</p> <p id="par5">Unchanged Paragraph</p> 

暂无
暂无

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

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