繁体   English   中英

输入更改时,onchange不会自动工作

[英]onchange doesn't work automatically when an input changes

我正在写一个JavaScript来根据用户输入来计算价格,并根据所计算的价格来计算总价格。 我不想放onchange =“ Total();” 进入用户输入,因为我希望合计功能自动区分价格输入的值变化。 有没有办法做到这一点?

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

如果您使用的是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.
}

您可以在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> 

我根据您的代码做了一个简单的小提琴 ,并在两个输入之间应用了一个事件。 第二个输入的分派类似于手动,因为它是只读的。

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;
                  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM