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

时间:2017-12-26 03:26:52

标签: javascript html text

我在使用JavaScript更改HTML中的文本内容后,试图加粗单词。

这是我的代码:



document.getElementById('par3').textContent = "I <b>love</b> JS";
&#13;
<!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>
&#13;
&#13;
&#13;

不知何故, 标签未呈现。这有什么特定的转义字符吗?或者这是更复杂的事情要做?

3 个答案:

答案 0 :(得分:2)

您需要使用innerHTMLtextContent将逃脱你的字符串。

&#13;
&#13;
document.getElementById('par3').innerHTML= "I <b>love</b> JS";
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

use innerHTML other then textContent or

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

答案 2 :(得分:0)

textContent将忽略字符串中的html标记。 使用innerHTML代替textContent

&#13;
&#13;
document.getElementById('par3').innerHTML = "I <b>love</b> JS";
&#13;
<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>
&#13;
&#13;
&#13;