2017-05-03 115 views
-2

请我有一个问题在这里我的工作,我有一个input场,并有button,我用它来创建新的inputonclick事件,但我的问题是如何将两个input字段中的数字相乘并提醒答案。如何multipy一个领域,一个新创建的领域之间的数字

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); 
} 
+0

这些变量的作用域的'create'函数内部,他们是不可用的'multiply'函数内。无论如何 - 你想要乘以一个DOM元素和一个数字吗? –

+0

尝试格式化您的代码时,我遇到了一个奇怪的逗号 - 是在复制/粘贴过程中发生错字,还是真的出现在代码中?(“main_input”)。value,'? – csmckelvey

+0

“_如何在两个输入字段中相乘并提醒answser_”您知道如何从字段中获取文本吗?你知道如何做两个数字的乘法吗?你知道如何做警报吗?哪个_步骤可以不完成? – csmckelvey

回答

0

使用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>

0

在缺乏清晰的,我张贴这种解决方案的价值。看起来你不是几个概念清楚,所以让我尝试解释一下它们:

  1. 您需要将您的变量创建的(范围),使他们在乘()函数可用。
  2. 你不能只乘以两个输入字段。您需要从它们中获取值,如下面的代码所示。

希望它可以帮助您前进!

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>