JS - 组合来自两个函数的值

时间:2016-10-04 22:36:18

标签: javascript html

如何组合两个函数的输出来对这两个值进行一些操作?

<div class="grid">
  <h2>Adjust the level</h2>
 <input 
        type="range" 
        name="points" 
        min="0" 
        max="10"
        step="1"
     onChange="xLevel(this.value)">
  <input 
        type="range" 
        name="points" 
        min="0" 
        max="10"
        step="1"
     onChange="yLevel(this.value)">
  <div id="output">
    <p id="x"></p>
    <p id="y"></p>
  </div>
</div>

JS是:

var output = document.getElementById("output");

var xout = document.getElementById("x");

var yout = document.getElementById("y");

function xLevel(newVal) {
  xout.innerHTML = newVal;
}
function yLevel(newVal) {
  yout.innerHTML = newVal;
}

那么如何将两个值x和y组合到例如。将它们相乘并在另一个div中显示它们?

由于

1 个答案:

答案 0 :(得分:0)

将新值存储在顶级作用域中的自己的变量中,然后在单独的函数中对它们进行操作。

var output = document.getElementById("output");

var xout = document.getElementById("x");

var yout = document.getElementById("y");

var multout = document.getElementById('mult');

var xval;
var yval;

function xLevel(newVal) {
  xout.innerHTML = newVal;
  xval = parseInt(newVal, 10); // casts it to a number
  updateMultiplier();
}
function yLevel(newVal) {
  yout.innerHTML = newVal;
  yval = parseInt(newVal, 10); // casts it to a number
  updateMultiplier();
}
function updateMultiplier() {
  multout.innerHTML = yval * xval;
}

然后是你的标记:

<div class="grid">
  <h2>Adjust the level</h2>
 <input 
        type="range" 
        name="points" 
        min="0" 
        max="10"
        step="1"
     onChange="xLevel(this.value)">
  <input 
        type="range" 
        name="points" 
        min="0" 
        max="10"
        step="1"
     onChange="yLevel(this.value)">
  <div id="output">
    <p id="x"></p>
    <p id="y"></p>
    <p id="mult"></p>
  </div>
</div>