用JS动态生成html,报错,第一次发帖,虚心求教!

Baby_Fisher 2013-10-13 06:03:52

<html>
<head>
<title>New Document </title>
<script type="text/javascript">

var inputtext=document.createElement("input");
var inputbutton=document.createElement("input");
inputtext.type="text";
inputtext.id="text";
inputbutton.type="button";
inputbutton.id="button";
inputbutton.value="按钮";
//inputbutton.onclick="button_onClick();";

console.error(inputtext);
console.error(inputbutton);
document.body.appendChild(inputtext);
document.body.appendChild(inputbutton);
function button_onClick(){
var txt = text.value;
var num = parseInt(txt);
for(var i=0;i<num;i++){
var element = document.createElement("A");
element.setAttribute("href","");
var br = document.createElement("BR");

var a = document.createTextNode(i+1);

element.appendChild(a);

document.body.appendChild(br);
document.body.appendChild(element);
}
}
</script>
</head>
<body>
</body>
</html>
...全文
133 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Baby_Fisher 2013-10-13
  • 打赏
  • 举报
回复
好吧我来了 2013-10-13
  • 打赏
  • 举报
回复
楼上说了 放到window.onload=function(){}
似梦飞花 2013-10-13
  • 打赏
  • 举报
回复
window.onload=function(){ //你的那段代码 } 不用html元素 不明白你的意思
Baby_Fisher 2013-10-13
  • 打赏
  • 举报
回复
那应该怎么修改呢?我不想用到html元素
似梦飞花 2013-10-13
  • 打赏
  • 举报
回复
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>New Document </title> <script type="text/javascript"> window.onload=function(){ var inputtext=document.createElement("input"); var inputbutton=document.createElement("input"); inputtext.type="text"; inputtext.id="text"; inputbutton.type="button"; inputbutton.id="button"; inputbutton.value="按钮"; //inputbutton.onclick="button_onClick();"; document.body.appendChild(inputtext); document.body.appendChild(inputbutton); function button_onClick(){ var txt = text.value; var num = parseInt(txt); for(var i=0;i<num;i++){ var element = document.createElement("A"); element.setAttribute("href",""); var br = document.createElement("BR"); var a = document.createTextNode(i+1); element.appendChild(a); document.body.appendChild(br); document.body.appendChild(element); } } } </script> </head> <body> </body> </html> 你append时body还没加载呢 所以出错了

87,907

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧