我想知道为什么这不起作用。我正在尝试在两个输入字段上设置ID,所以我可以抓住它,然后在函数中使用它。我可以创建元素然后设置ID,但我的任务要求我这样做(学校项目)。
var div = document.getElementById('div');
var p = document.createElement('p');
var butt = document.createElement('input');
var inputOne = document.createElement('input');
var inputTwo = document.createElement('input');
div.appendChild(inputOne);
div.appendChild(inputTwo);
inputOne.SetAttribute="type","text";
inputOne.placeholder="Something";
inputTwo.SetAttribute="type","number";
inputTwo.placeholder="SomethingElese";
butt.type="button";
butt.value="clickMe!";
div.appendChild(butt);
butt.onclick=func();
inputOne.SetAttribute="id","MyID";
function func(){
var text = document.getElementById('MyID').value;
alert(text);
}
答案 0 :(得分:0)
由于错误。
var div = document.getElementById('div');
var p = document.createElement('p');
var butt = document.createElement('input'); // really? I can think of better names
var inputOne = document.createElement('input');
var inputTwo = document.createElement('input');
div.appendChild(inputOne);
div.appendChild(inputTwo);
inputOne.setAttribute("type","text"); // call this as a function with a lowercase "setAttribute"
inputOne.placeholder="Something";
inputTwo.setAttribute("type","number"); // this too
inputTwo.placeholder="SomethingElese";
butt.type="button";
butt.value="clickMe!";
div.appendChild(butt);
butt.onclick=func; // pass the function by reference, not calling it
inputOne.setAttribute("id","MyID"); // again
答案 1 :(得分:0)
我现在就开始工作了。这是结果代码 - 谢谢!
var div = document.getElementById('myDiv');
var butt= document.createElement('input');
var inputOne = document.createElement('input');
var inputTwo = document.createElement('input');
div.appendChild(inputOne);
div.appendChild(inputTwo);
inputOne.setAttribute("type","text");
inputOne.placeholder="Something";
inputTwo.setAttribute("type","number");
inputTwo.placeholder="SomethingElse";
butt.type="button";
butt.value="ClickMe";
div.appendChild(butt);
butt.onclick=func;
inputOne.setAttribute("id","MyID");
function func(){
var text = document.getElementById('MyID').value;
alert(text);
}