<!doctype html>
<html>
<head>
<script>
function buildChat(name) {
var chat = document.getElementById('CreateChat');
var group = document.createElement('div');
var title = document.createElement('p');
title.className = 'title';
title.innerHTML = name;
title.align = 'center';
group.appendChild(title);
chat.appendChild(group);
}
buildChat('name');
</script>
</head>
<body>
<div id='CreateChat'></div>
</body>
</html>
CreateChat是正文中div标签的id。但是在控制台中它说聊天是空的,并且没有创建标签。谁能告诉我为什么?
答案 0 :(得分:0)
在加载CreateChat div之前,正在调用buildChat()。将脚本块向下移动到关闭正文标记的正上方,它应该可以正常工作。
答案 1 :(得分:0)
您应该将脚本直接放在结束</body>
标记或/和document.onload = function(){}之上。
在您调用函数时,该元素不存在。
<!doctype html>
<html>
<head>
</head>
<body>
<div id='CreateChat'></div>
<script>
function buildChat(name) {
var chat = document.getElementById('CreateChat');
var group = document.createElement('div');
var title = document.createElement('p');
title.className = 'title';
title.innerHTML = name;
title.align = 'center';
group.appendChild(title);
chat.appendChild(group);
}
buildChat('name');
</script>
</body>
</html>
答案 2 :(得分:0)
除了您的script
标记位于html div
元素上方之外,您还需要将“group”附加到DOM:
<!DOCTYPE html />
<html>
<head>
</head>
<body>
<div id='CreateChat'></div>
<script>
function buildChat(name) {
var chat = document.getElementById('CreateChat');
var group = document.createElement('div');
var title = document.createElement('p');
title.className = 'title';
title.innerHTML = "<p>" + name + "</p>";
title.align = 'center';
document.body.appendChild(group);
//^ Need to append group
group.appendChild(title);
chat.appendChild(group);
}
buildChat('name');
</script>
</body>
</html>