appendChild用法,变量数组Javascript

时间:2015-08-07 15:53:32

标签: javascript html5 appendchild

尝试使用appendChild在一个段落中创建一个子元素,我想我在这里缺少一些基本的东西,但我无法弄清楚是什么,也不确定我是否正确使用了appendChild。

<!DOCTYPE html>
<html>
<body>

<p>Accessing Variables from an Array</p>

<p id="demo"></p>

<script>
var employees = [
    {
    "firstName":"John",
    "lastName":"Doe"
    }, 
    {
    "firstName":"Anna",
    "lastName":"Smith"
    },
    {
    "firstName":"Peter",
    "lastName":"Jones"
    }
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;


childtest=document.getElementById("demo").innerHTML=employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>

</body>
</html>

我要做的是创建一个“demo”的子项,并获取第二个员工阵列,并将其作为子元素并输出到第一个输出下面。

3 个答案:

答案 0 :(得分:1)

WORKOBJECTSVALS不是此处的元素。

childtest

答案 1 :(得分:1)

您的问题是您没有创建新元素,而.innerHTML只是覆盖现有

fiddle

var employees = [{
    "firstName": "John",
        "lastName": "Doe"
}, {
    "firstName": "Anna",
        "lastName": "Smith"
}, {
    "firstName": "Peter",
        "lastName": "Jones"
}];
document.getElementById("demo").innerHTML = employees[0].firstName + " " + employees[0].lastName;



var newEl = document.createTextNode(employees[1].firstName);
first = document.getElementById("demo");
first.appendChild(newEl);

答案 2 :(得分:0)

Katpoes说得对,只是为了澄清,这有效:

<!DOCTYPE html>
<html>
<body>

<p>How to create a JavaScript object array.</p>

<p id="demo"></p>

<script>
var employees = [
    {
    "firstName":"John",
    "lastName":"Doe"
    }, 
    {
    "firstName":"Anna",
    "lastName":"Smith"
    },
    {
    "firstName":"Peter",
    "lastName":"Jones"
    }
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
var childtest=document.createElement("p");
childtest.innerHTML = employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>

</body>
</html>