2017-05-03 87 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>