请我在工作中有一个问题,我有一个input
字段,并且有一个button
,我用来使用onclick
事件来创建新的input
字段,但我的问题是如何在input
字段都提醒答案。
function create(){
var main_input = document.getElementById("main_input").value,
newinput = document.createElement('input');
newinput.placeholder = "test1";
newinput.value;
document.getElementById("mytest").appendChild(newinput);
}
function multiply(){
var ans = newinput * main_input;
alert(ans);
}
在没有清晰度的情况下,我正在发布此解决方案。看来您对几个概念并不清楚,所以让我尝试解释它们:
- 您需要将变量移动到create((范围之外,以便它们可以在乘数((函数中可用。
- 您不仅要乘以两个输入字段。您需要从下面的代码中获取它们的值。
希望它可以帮助您前进!
var main_input,newinput;
function create(){
main_input = document.getElementById("main_input");
newinput = document.createElement('INPUT');
newinput.placeholder = "test1";
newinput.value = 10;
document.getElementById("mytest").appendChild(newinput);
}
function multiply(){
var ans = newinput.value * main_input.value;
alert(ans);
}
create();
multiply();
<input id="main_input" value=10 />
<div id="mytest"></div>
使用eval((,也可以手动乘以 input1.value * input2.value
function create(){
// this is unnecessary, you are creating a new element
// var main_input = document.getElementById("main-input");
var newinput = document.createElement('input');
newinput.placeholder = "test1";
newinput.id = 'test1'; // give the element an id, to access it later by id
// newinput.value; // this too is unnecessary, you'll get the value from the user
if (!document.getElementById('test1')) {
// append the child only if it doesn't exist
document.getElementById("mytest").appendChild(newinput);
}
}
function multiply(){
var newinput = document.getElementById('test1');
var mainInput = document.getElementById("main_input");
alert(eval(newinput.value + '*' + mainInput.value));
// alert(newinput.value * mainInput.value) you can also use this method
}
<div id="mytest">
<input type="text" id="main_input">
</div>
<button onclick="create()">Create</button>
<button onclick="multiply()">Multiply</button>