使用JavaScript操作DOM



下面的代码应该向我的文档添加一个p元素,向该元素添加文本,并将元素的字体颜色更改为red

这是上课用的。我已经为此工作了两个小时,但被难住了。

<!DOCTYPE html>
<html>
<body>
<h1 id='demo'>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container">
<div class="content">
This is the glorious text-content!
</div>
</div>

</body>
<script>
const p = document.createElement('p');
p.textContent = 'Hey, I'm red.';
p.style.color = 'red';
div.content.appendChild('p');
</script>
</html>

代码没有产生所需的结果。你们中有谁能帮我理解我缺少什么吗?

'Hey, I'm red.';中,您需要使用反斜杠转义'm之前的引号,否则您可以放在双引号内。

除了div.content.appendChild('p');之外,div还需要成为一个目标,您可以使用document.getElementById&在appendChild中,您需要将p作为变量传递

const p = document.createElement('p');
p.textContent = 'Hey, I'm red.';
p.style.color = 'red';
document.getElementById('container').appendChild(p);
<h1 id='demo'>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container">
<div class="content">
This is the glorious text-content!
</div>
</div>

您的代码中几乎没有问题:

  1. 您正在使用的textContent('Hey, I'm red.'(无效。

    可以使用双引号将整个字符串括起来,这样就可以像"Hey, I'm red."一样在字符串内部使用单引号。

    或者:您可以使用反斜杠((来转义内部引号,如'Hey, I'm red.'

    或者:您可以使用Template Literals将字符串包装为反勾号,如:

    `Hey, I'm red.`
    
  2. 您必须使用document.getElementById()来定位元素。

  3. 您还必须删除appendChild('p')中变量p周围的引号,否则引号会将其视为字符串,而不是变量

const p = document.createElement('p');
p.textContent = "Hey, I'm red.";
p.style.color = 'red';
document.getElementById('container').appendChild(p);
<h1 id='demo'>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container">
<div class="content">
This is the glorious text-content!
</div>
</div>

最新更新