简体   繁体   English

为什么我的函数无法获取变量的值?

[英]Why does my function not fetch the value of variable?

The purpose of the code is to compute for the car market value. 该代码的目的是计算汽车的市场价值。 If If Age of the Car is : 1 - then subtract 20% from the Price of the Car 2 - then subtract 35% from the Price of the Car 3 - 7 - then subtract 35% from the Price of the Car and then subtract 10% more for each year starting from the 3rd year. 如果“汽车年龄”为:1-然后从汽车价格中减去20%2-然后从汽车价格中减去35%3-7-然后从汽车价格中减去35%,然后减去10从第三年开始,每年增加%。 8 - 10 - then the market value is fixed at 100,000.00 More than 10 years then the market value is fixed at 75,000.00. 8-10-那么市场价值固定为100,000.00。超过10年,市场价值固定为75,000.00。

Then it will display the name inputted and the value of the car but it doesnt seem to work. 然后它将显示输入的名称和汽车的价格,但它似乎不起作用。 pls help 请帮助

 var price = document.getElementById("price").value; var age = document.getElementById("age").value; var condition = document.getElementById("condition").value; var name = document.getElementById("name").value; age = parseInt(age); condition = parseInt(condition); function calculateValue() { switch (age) { case 0: price = price - 0.20 * price; break; case 1: price = price - 0.35 * price; break; case 2: price = price - 0.35 * price - (age - 3) * .10 * price; break; case 3: price = 100000; break; case 4: price = 75000; break; } switch (condition) { case 0: price = price; break; case 1: price = price - price * .10; break; } document.getElementById("message").innerHTML = "Your" + name + " is valued at " + price + "today"; } 
 <h1>Car Market Value Calculator</h1> <form> Car Brand:<input id="name" type="text" name="name" placeholder="Please input car brand" autofocus required><br> Age of Car <select id="age"> <option value="0">1</option> <option value="1">2</option> <option value="2">3-7</option> <option value="3">8-10</option> <option value="4">more than 10</option> </select><br> Price of Car<input id="price" type="number" name="price" placeholder="minimum:300,000" min="300000"><br> <p>Good Condition?</p> Yes <input id="condition" type="radio" name="condition" value="0"> No <input id="condition" type="radio" name="condition" value="1"> <button type="button" name="submit" onclick="calculateValue()">Submit</button> </form> <p id="message"></p> 

You have a few errors in your code: 您的代码中有一些错误:

  1. You're not getting the input from the dom at the right moment. 您没有在适当的时候从dom接收输入。 You should get the input values before calculation, not when the script loads. 您应该在计算之前获取输入值,而不是在脚本加载时获取输入值。 This ensures that the DOM is loaded, and get the right values. 这样可以确保DOM已加载,并获得正确的值。

  2. The age value is not calculated properly. age值计算不正确。 Don't use select for numeric values. 不要将select用于数值。 Also, read again your case price = 2 ;) 另外,再次读取您的case price = 2 ;)

This code does what you expect: 这段代码符合您的期望:

 const calculateValue = () => { let age = +document.querySelector('input[name=age]').value, price = +document.querySelector('input[name=price]').value, condition = document.querySelector('input[name=condition]').checked; // depreciate based on age if (age==1) price*=.8 else if (age==2) price*=.65 else if (age>2 && age<8) price*=(.65-(age-3)*.1) else if (age>7 && age<11) price = 100000 else price = 75000; // depreciate based on condition if (!condition) price*=.9; console.log(price); } 
 <div> <input name="age" type="number" placeholder="age"> </div> <div> <input name="price" type="number" placeholder="price"> </div> <div> Good condition? <input name="condition" type="radio" value="true" checked>yes <input name="condition" type="radio" value="false">no </div> <button onclick="calculateValue()">Compute</button> 

If you open your browser's development console you'll see an error indicating that you're trying to get the .value of something that is null or undefined. 如果打开浏览器的开发控制台,则会看到一条错误消息,表明您正在尝试获取null或未定义内容的.value Because document.getElementById("price") doesn't find anything when you're executing it. 因为document.getElementById("price")在执行时找不到任何东西。

You're trying to get the values of your inputs before the user has typed anything. 您正在尝试在用户键入任何内容之前获取输入的值。 Before the inputs have even been rendered on the page even. 甚至在页面上呈现输入之前。

You don't want to get the values until the user has pressed the button. 在用户按下按钮之前,您不需要获取值。 So move that code into the function: 因此,将代码移入函数:

function calculateValue() {
    var price = document.getElementById("price").value;
    var age = document.getElementById("age").value;
    var condition = document.getElementById("condition").value;
    var name = document.getElementById("name").value;

    age = parseInt(age);
    condition = parseInt(condition);

    //... the rest of your function
}

You need to move the first 6 lines where you are trying to get the values from input inside your calculateValue() function 您需要将前6行移动到尝试从calculateValue()函数内部的输入中获取值的位置

function calculateValue() {
  var price = document.getElementById("price").value;
  var age = document.getElementById("age").value;
  var condition = document.getElementById("condition").value;
  var name = document.getElementById("name").value;

  age = parseInt(age);
  condition = parseInt(condition);

  switch (age) {
  ...

Simply do this and your code will work fine. 只需执行此操作,您的代码即可正常工作。

Explanation: You need to get the new values from the input boxes each time the submit button is pressed. 说明:每次按下提交按钮时,都需要从输入框中获取新值。 What you have done is that you have taken the values from the input boxes only once. 您所做的是仅从输入框中获取了一次值。 As you move these lines inside the function, the fresh values are taken each time the button is pressed. 在函数中移动这些行时,每次按下按钮都会获取新值。

The document.getElementById commands will execute before the HTML markup is loaded, and hence will trigger an error. document.getElementById命令将在加载HTML标记之前执行,因此将触发错误。 You can fix it by moving the variable declarations and value-fetching into the function: 您可以通过将变量声明和值获取移入函数来解决此问题:

function calculateValue() {
    var price = document.getElementById("price").value;
    var age = document.getElementById("age").value;
    var condition = document.getElementById("condition").value;
    var name = document.getElementById("name").value;

    age = parseInt(age);
    condition = parseInt(condition);


    switch (age) {
        case 0:
...etc...

You will want to do this anyway, since your code needs to fetch the current input values every time you click "submit". 无论如何,您还是要这样做,因为您的代码每次单击“提交”时都需要获取当前输入值。

Get values of your variables inside the calculate value function 在计算值函数中获取变量的值

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="description" content="Car Market Value Calculator">
        <meta name="keywords" content="calculator, car, market, value">
        <meta name="author" content=", 26/02/19">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>

        </style>

    </head>

    <body>
        <h1>Car Market Value Calculator</h1>
        <form>
            Car Brand:<input id="name" type="text" name="name" placeholder="Please input car brand" autofocus required><br>
            Age of Car<select id="age">
                <option value="0">1</option>
                <option value="1">2</option>
                <option value="2">3-7</option>
                <option value="3">8-10</option>
                <option value="4">more than 10</option>                 
            </select><br>
            Price of Car<input id="price" type="number" name="price" placeholder="minimum:300,000" min="300000" ><br>
            <p>Good Condition?</p>
            Yes <input id="condition" type="radio" name="condition" value="0">
            No  <input id="condition" type="radio" name="condition" value="1">
            <button type="button" name="submit" onclick = "calculateValue()">Submit</button>

        </form>
        <p id="message"></p>
    </body>

    <script>


        function calculateValue(){
            var price = document.getElementById("price").value;
            var age = document.getElementById("age").value;
            var condition = document.getElementById("condition").value;
            var name = document.getElementById("name").value;

            age = parseInt(age);
            condition = parseInt(condition);
            alert(price);
            switch (age) {
                    case 0:
                        price = price - 0.20*price;
                    break;
                    case 1:
                        price = price - 0.35*price;
                    break;
                    case 2:
                        price = price - 0.35*price - (age-3)*.10*price;
                    break;
                    case 3:
                        price = 100000;
                    break;
                    case 4:
                        price = 75000;
                    break;
                }

            switch(condition){
                case 0:
                    price = price;
                break;
                case 1:
                    price = price- price*.10;
                break;
            }

            document.getElementById("message").innerHTML = "Your"+ name +" is valued at "+price+"today";
        }
        </script>

</html>

Every time you click the submit you need to get the input values again, and not only when loading the page. 每次单击提交时,不仅在加载页面时,还需要再次获取输入值。 Just move the 'var' declarations into the function: 只需将'var'声明移至函数中:

function calculateValue() {
  var age = document.getElementById("age").value;
  var condition = document.getElementById("condition").value;
  var price = document.getElementById("price").value;
  var name = document.getElementById("name").value;

  age = parseInt(age);
  condition = parseInt(condition);

  switch (age) {
    case 0:
      price = price - 0.20 * price;
      break;
    case 1:
      price = price - 0.35 * price;
      break;
    case 2:
      price = price - 0.35 * price - (age - 3) * .10 * price;
      break;
    case 3:
      price = 100000;
      break;
    case 4:
      price = 75000;
      break;
  }

  switch (condition) {
    case 0:
      price = price;
      break;
    case 1:
      price = price - price * .10;
      break;
  }

  document.getElementById("message").innerHTML = "Your" + name + " is valued at " + price + "today";
}

Solution at Codepen Codepen解决方案

function calculateValue() {
    var price = document.getElementById("price").value;
    var age = document.getElementById("age").value;
    var condition = document.getElementById("condition").value;
    var name = document.getElementById("name").value;
    age = parseInt(age);
    condition = parseInt(condition);
    switch (age) {
        case 0:
            price = price - 0.20 * price;
            break;
        case 1:
            price = price - 0.35 * price;
            break;
        case 2:
            price = price - 0.35 * price - (age - 3) * .10 * price;
            break;
        case 3:
            price = 100000;
            break;
        case 4:
            price = 75000;
            break;
    }
    switch (condition) {
        case 0:
            price = price;
            break;
        case 1:
            price = price - price * .10;
            break;
    }
    document.getElementById("message").innerHTML="Your"+name+" is valued at "+price+ " 
    today";
}`

The comments given by others are correct. 其他人的评论是正确的。 You need to get the updated values on click of the submit button and hence all the variable will come inside the calculateValue function. 您需要单击“提交”按钮来获取更新的值,因此所有变量都将进入calculateValue函数内。

Wrap all the code in the document.ready method. 将所有代码包装在document.ready方法中。

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

相关问题 为什么我的 addEventListener function 为变量在本地而不是全局赋值? - Why does my addEventListener function assign a value to a variable locally, but not globally? 为什么在我的 React 应用程序中无法获取 function - Why the fetch function does not work from my React app 为什么我的函数的值不随对象的值更新 - Why the value of my function does not update with the value of my object 为什么我的本地存储函数不更新变量? - Why does my local storage function does not update variable? 为什么我的变量值在Logger.log中更改 - why does my variable value change in Logger.log 为什么我的全局变量在函数之间不携带其值 - why does my global variable not carry its value between functions 为什么我的JavaScript函数看到mouseevent而不是空变量? - Why does my JavaScript function see a mouseevent instead of an empty variable? 为什么这个变量在我执行“函数MyVar(){}”之前有一个值? - Why does this variable have a value before I do “function MyVar() {}”? 为什么函数返回本地JSON变量的值而不是全局? - Why does the function return the value of the local JSON variable instead the global? 为什么我的变量没有从 JS function 获得赋值? - Why my variable not getting assigned value from JS function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM