如何使用JS和DOM创建元素,设置属性,使用innerHTML和appendChild

Ben*_*enP 5 html javascript dom innerhtml appendchild

我正在用HTML/JS编写一个示例程序来演示创建用户定义对象(属性/值)的数组,创建元素,使用innerHTML从对象数组添加数据,然后附加新填充的元素以使用它来打印它的appendChild();

出于某种原因,除了我的硬编码调试之外,运行程序不提供任何输出.鉴于语言,查看源也不是很有用.

请原谅我这个简单的问题,我是JS的新手,花了很多时间阅读很多资源 - 我觉得我可能会遗漏一些小事.

谢谢!!

<title>
This is my title.
</title>

<body>
<p>xXx<br/></p>
<script>

var array = new Array();

var thing1 = {
property: "value-1"
};

        var thing2 = {
        property: "value-2"
        };


        array.push(thing1);
        array.push(thing2);

        for (index = 0; index < array.length; ++index) {

            test_el = document.createElement("p");

            test_el.innerHTML(array[index].property);

            document.body.appendChild(test_el);

        };
        //I wish to print 'value' text into the body from my object, that is all

</script>
</body>
Run Code Online (Sandbox Code Playgroud)

Pie*_*ini 6

你的错误似乎是innerHTML,这不是一个函数,所以你应该把这个值等于某个东西.我已更正您的代码,以便您可以看到结果.

var array = new Array();
var thing1 = {
  property: "value-1"
};
var thing2 = {
  property: "value-2"
};

array.push(thing1);
array.push(thing2);

for (index = 0; index < array.length; ++index) {
  test_el = document.createElement('p');

  test_el.innerHTML = array[index].property;

  document.body.appendChild(test_el);
};
Run Code Online (Sandbox Code Playgroud)
<title>
  This is my title.
</title>

<body>
  <p>xXx<br/></p>
</body>
Run Code Online (Sandbox Code Playgroud)