1

我正在尝试一个简单的练习,我想在其中附加一个

,由 JavaScript 生成到 id 为“target-area”的 div。问题是 Chrome 拒绝注入这一段并给我一个错误: Uncaught TypeError: Object # has no method 'createTextNode'

这是代码:

<html>
<head>
    <title>JS</title>

</head>
<body>
    <div id="target-area">
        <p id="tagline">Hello World!</p>
    </div>

</body>
<script type="text/javascript">

        // store the target area to a variable to keep things neat
        var targetArea = document.getElementById("target-area");
        // create our <p> element
        var p = document.createElement("p");
        // create a text node inside the <p>, note that we're using a variable "p" here
        var snippet = p.createTextNode("this was a generated paragraph");
        // insert our generated paragraph into the DOM
        targetArea.appendChild(snippet);

    </script>
</html>

谢谢!

4

2 回答 2

3

文档具有 createTextNode属性,而不是刚刚创建的元素

所以基本上你的代码应该是这样的..

    // store the target area to a variable to keep things neat
    var targetArea = document.getElementById("target-area");
    // create our <p> element
    var p = document.createElement("p");
    // create a text node inside the <p>, note that we're 
    //  using a variable "p" here
   var snippet = document.createTextNode("this was a generated paragraph");
    // insert our generated paragraph into the DOM
    p.appendChild(snippet);
    targetArea.appendChild(p);

检查小提琴

于 2013-05-14T17:43:27.363 回答
0

只是出于好奇。

为什么不简单呢?

// store the target area to a variable to keep things neat
var targetArea = document.getElementById("target-area");
// create our <p> element
var p = document.createElement("p");
// create a text node inside the <p>, note that we're 
//  using a variable "p" here
var snippet = document.createTextNode("this was a generated paragraph");
// insert our generated paragraph into the DOM
targetArea.appendChild(snippet);
于 2016-12-01T16:19:30.633 回答