【发布时间】:2019-06-06 20:01:42
【问题描述】:
我正在用 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>
【问题讨论】:
-
您的变量是
test_el,但您附加了text_el。我想这会在控制台中引发错误吗? -
啊-谢谢!好眼力。不幸的是 - 修复后我仍然得到一个空白屏幕。这应该很容易运行,不是吗?
-
你看过你的控制台了吗?你有一个错误:“Uncaught TypeError: test_el.innerHTML is not a function”。您可以通过
.innerHTML = ...而不是innerHTML( ... )来更改元素的 HTML。 -
我不知道我能做到这一点!得到它的工作。我爱你。
-
控制台是你最好的朋友!在您的页面上按
F12以查看它(或在Chrome 中按CTRL+SHIFT+J)。例如,如果您想跟踪某物的价值,可以使用console.log(test_el)。
标签: javascript html dom innerhtml appendchild