简体   繁体   English

如何将值传递给 JavaScript 中的 function?

[英]How do I pass a value to a function in JavaScript?

I have this code that changes the value of a variable called "factor" based upon a dropdown list selection:我有这段代码可以根据下拉列表选择更改名为“factor”的变量的值:

sel.addEventListener("change", function (evt) {
      var days = parseInt(evt.target.options[evt.target.selectedIndex].value);
      var factor = 0;
       switch (days) {
        case 3: case 4: var factor = 1.5; break;
        case 5: case 6: var factor = 1.4; break;
        case 7: case 8: case 9: var factor = 1.3; break;
        case 10: case 11: case 12: case 13: case 14: var factor = 1.2; break;
        case 15: default: var factor = 1.0;
      }

Then, I have this function that is supposed to use the variable called "factor" in a calculation based upon another (different) dropdown list selection:然后,我有这个 function,它应该在基于另一个(不同的)下拉列表选择的计算中使用名为“factor”的变量:

psel.addEventListener("change", function (evt) {});
     function calculate (pfactor){
     var nopages = document.getElementById("pages");
     var priceOutput = document.getElementById("nopagesOutput");
     var pfactor = document.getElementById("factorOutput");
     priceOutput.innerHTML = nopages.value;

     var total = nopages.value * 10 * factor;
     document.getElementById("savings").innerHTML = `$ ${total}`;

I keep getting NaN as the result.结果我一直得到 NaN 。 How do I use the value in the variable called "factor" in the calculate();如何在 calculate() 中使用名为“factor”的变量中的值; function? function?

Since there there was no HTML posted, the example has an optimal layout which includes:由于没有发布 HTML,该示例具有最佳布局,其中包括:

  • <form> - always wrap everything in a <form> if there is more than one form control <form> - 如果有多个表单控件,则始终将所有内容包装在<form>
  • <input type='range'> for the days <input type='range'> days
  • 2 <output> - one to display number of days and one to display saved 2 <output> - 一个显示days ,一个显示saved
  • <input type='number'> for price <input type='number'> price

Details are commented in example详细信息在示例中进行了注释

 // Reference the <form> const form = document.forms[0]; // Initialize output.view form.elements.view.value = '3'; // Bind the <form> to the "input" event form.addEventListener("input", function (evt) { // Reference all form controls const IO = this.elements; let factor; // Declare factor let price = +IO.price.value // Get price as a number let days = +IO.days.value; // Get days as a number IO.view.value = days; // Display number of days switch(days) { case 3: case 4: factor = 1.5; break; case 5: case 6: factor = 1.4; break; case 7: case 8: case 9: factor = 1.3; break; case 10: case 11: case 12: case 13: case 14: factor = 1.2; break; case 15: default: factor = 1.0; } // Call calculate - pass 2 numbers and a HTMLCollection calculate(factor, price, IO); }); function calculate(factor, price, IO) { // Calculate parameters into a string with 2 decimals const total = (factor * price * 10).toFixed(2); // Display calculation IO.saved.value = '$'+total; }
 label { display: block; margin-bottom: 12px; } input { font: inherit; } #days { vertical-align: sub; } #price { width:9ch; text-align: right; }
 <form> <label>Factor:&nbsp; <input id='days' type='range' min='3' max='15' step='1' value='3'> &nbsp;<output id='view' value='3'></output> Days </label> <label>Price:&nbsp; <input id='price' type='number' min='.01' step='any' value='.01'> </label> <label>Savings:&nbsp; <output id='saved'></output> </label> </form>

You can move factor variable to the outer scope that will share among functions您可以将factor变量移动到将在函数之间共享的外部 scope

var factor = 0; //move `factor` from the function scope to the global scope

sel.addEventListener("change", function (evt) {
      var days = parseInt(evt.target.options[evt.target.selectedIndex].value);
      //var factor = 0; //remove this
       switch (days) {
        case 3: case 4: var factor = 1.5; break;
        case 5: case 6: var factor = 1.4; break;
        case 7: case 8: case 9: var factor = 1.3; break;
        case 10: case 11: case 12: case 13: case 14: var factor = 1.2; break;
        case 15: default: var factor = 1.0;
      }

Now factor is visible in calculate , but you have another problem with your calculation is nopages.value .现在factorcalculate中可见,但是你的计算还有另一个问题是nopages.value That value is possibly a string which cannot proceed number operations, so you need to convert it to a number by Number(nopages.value)该值可能是一个不能进行数字运算的字符串,因此您需要将其通过Number(nopages.value)转换为数字

     function calculate (pfactor){
     var nopages = document.getElementById("pages");
     var priceOutput = document.getElementById("nopagesOutput");
     var pfactor = document.getElementById("factorOutput");
     priceOutput.innerHTML = nopages.value;

     var total = Number(nopages.value) * 10 * factor;
     document.getElementById("savings").innerHTML = `$ ${total}`;

The factor variable is declared local to the sel change event, so is not visible in the psel event.因子变量被声明为 sel 更改事件的局部变量,因此在 psel 事件中不可见。 You need to declare the factor variable outside of the event methods, or save to a hidden input type in sel, and get it from hidden input in psel.您需要在事件方法之外声明因子变量,或者保存到sel中的隐藏输入类型,并从psel中的隐藏输入中获取它。 Plus you just need the one var declaration, in the switch you don't need the var keyword, since factor has already been declared (var factor = 0)另外,您只需要一个 var 声明,在 switch 中您不需要 var 关键字,因为已经声明了 factor (var factor = 0)

In html在 html

<input type="hidden id ="factor"/>

at bottom of sel在 sel 的底部

document.getElementById("factor").value = factor;

In psel在psel中

var factor = document.getElementById("factor").value 

or just declare或者只是声明

var factor = 0 

outside of the events (depending how your code is structured)在事件之外(取决于您的代码的结构)

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

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