2017-08-01 73 views
0

我写了一个JavaScript来计算基于用户输入的价格和基于计算出的价格的总价格。我不想把onchange =“Total();”进入用户输入,因为我希望Total函数自动区分价格输入的值更改。有没有办法做到这一点?当输入变化时,onchange不会自动工作

<html> 
    user input:<input type="text" id="user-input" onchange="price();"><br> 

    price:<input type="text" id="calculation" onchange="Total();" readonly> 
    <br> 


    Total:<input type="text" id="result" readonly><br> 

    </html> 

      <script> 
     function price() { 

     var a = parseInt(document.getElementById('user-input').value), 
      b = document.getElementById('calculation'); 


      b.value = a + 10; 

       } 



     function Total() { 
      var b = parseInt(document.getElementById('calculation').value), 
       c = document.getElementById('result'); 

       c.value = b*2; 
        } 

        </script> 
+2

如果您看到您的要求,您的问题是完全误导 –

回答

0

我做了一个简单的fiddle,在你的代码的基地和两个输入端之间施加的事件。第二次输入的调度就像手动,因为是只读的。

function price() { 

     var a = parseInt(document.getElementById('user-input').value), 
      b = document.getElementById('calculation'); 


      b.value = a + 10; 
      if (b.onchange) 
          b.onchange(); 
       } 



     function Total() { 
     console.log('binded'); 
      var b = parseInt(document.getElementById('calculation').value), 
       c = document.getElementById('result'); 

       c.value = b*2; 
        } 
+0

优秀。这正是我想要的。谢谢 –

0

如果您正在使用jQuery尝试使用委托。这是一个简单的例子。

以下是html。

user input:<input type="text" id="user-input"> 

以下是javascript。

$("body").delegate("#user-input", "onchange", function() { 
    //your code here. 
}); 

我的回答只会让onchange()事件火,你必须代码逻辑的其余部分。

这是另一个使用JavaScript的例子。我试过了,它工作正常。

以下是html代码。

<input type="text" id="userinput" onchange="price();"> 

以下是JavaScript函数。

function price() 
{ 
    //your code here. 
} 
+0

您确定OP使用jQuery吗? –

+0

是否有与此“委托”相同的JavaScript代码? –

+0

我假设他正在使用JQuery。 –

0

可以在price()执行,而不必单独Total()所有的计算。由于priceresult都是readonly,用户无法真正更改它们中的值。因此,只需将代码从Total()移动到price(),它就可以为您工作。下面是更新后的代码:

function price() { 
 
    var a = parseInt(document.getElementById('user-input').value), 
 
    b = document.getElementById('calculation'), 
 
    c = document.getElementById('result') 
 
    b.value = a + 10; 
 
    c.value = b.value * 2; 
 
}
user input:<input type="text" id="user-input" onchange="price();"><br> price: 
 

 
<input type="text" id="calculation" readonly> 
 
<br> Total: 
 
<input type="text" id="result" readonly><br>

相关问题