-4

我正在学习 javascript,我对创建元素感到震惊。它在任何浏览器中都不起作用。这是我的代码:

<body>
<div id="cont">
<script type="text/javascript">
function hi()
{
    alert("hi");
}
function replace()
{
    var a=document.getElementById('cont');
    var b=new Element("form",{name:"pnrForm",action:"\frame.html",method:"post"});
    var c=new Element("input",{name:"lccp_trnname",type:"text",id:"lccp_trnname",size:"15",maxlength:"15",alt:"Train Name/Number"});
    var d=new Element("input",{type:"image",name:"getIt",src:"button-get-pnr.png",align:"middle"});
    b.appendChild(c);
    b.appendChild(d);
    a.appendChild(b);
}
replace();
hi();
</script>
</div>
</body>
4

2 回答 2

3

我相信您的代码期望 Mootools 存在。试试这个:

<body>
<div id="cont">
<script src="//ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js"></script>
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<script type="text/javascript">
function hi()
{
    alert("hi");
}
function replace()
{
    var a=document.getElementById('cont');
    var b=new Element("form",{name:"pnrForm",action:"\frame.html",method:"post"});
    var c=new Element("input",{name:"lccp_trnname",type:"text",id:"lccp_trnname",size:"15",maxlength:"15",alt:"Train Name/Number"});
    var d=new Element("input",{type:"image",name:"getIt",src:"button-get-pnr.png",align:"middle"});
    b.appendChild(c);
    b.appendChild(d);
    a.appendChild(b);
}
replace();
hi();
</script>
</div>
</body>

MooTools不是DOM,也不是document.createElement

于 2012-08-22T08:47:05.807 回答
0

使用document.createElement(见演示:http: //jsfiddle.net/WQaaY/1):

function replace() {
  var div = document.getElementById('div');

  var form = document.createElement('form');
  form.name = "pnrForm";
  form.action = "\frame.html"
  form.method = "post";

  var a = document.createElement('input');
  a.id = "lccp_trnname";
  a.type = "text";
  a.name = "lccp_trnname";
  a.alt = "Train Name/Number";
  a.size = "15";
  a.maxlength = "15";

  var b = document.createElement('input');
  b.type = "image";
  b.name = "getIt";
  b.src = "button-get-pnr.png";
  b.align = "middle";

  form.appendChild(a);    
  form.appendChild(b);
  div.appendChild(form);
}

replace();
​
于 2012-08-22T08:51:52.687 回答