简体   繁体   中英

How can I make a button do math and then display it using JS?

Basically, I' trying to get the "Turn Left" button to display a "left turn" where the direction will decrease by 10 every time the user clicks the button (for ex.: first click = 170, second click = 160, third click = 150, etc.) and it will be displayed in the browser. I also want to make a "Turn Right" button to do the same thing, except it ADDS 10 to the last direction displayed. Also, this didn't happen at first, but I now see an error when I'm inspecting the elements in the browser that says the "Vehicle" in the HTML is not defined. Any idea what happened there?

Here's the HTML:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8" />
    <title>My Vehicles</title>
</head>

<body>

<div id="input">

<br/>
<br/>
<br/>
    <input type="text" id="engstart"> Pick Your Starting Speed</input>
    <br/>
    <button onclick="startEngine()"> Start the Car </button>
<br/>
<br/>
    <button onclick="accel()"> Accelerate </button>
<br>
<br/>
    <button onclick="carInBrake()"> Put Car In Brake </button>
<br/>
<br/>
    <button onclick="left()"> Turn Left </button>

</div>
<div id="displays">


    <script src="vehicle.js">
    </script>

    <script>

        let pickColor = prompt("Pick a color");
        //let num = prompt("Pick your starting speed in mph");
        let num = document.getElementById('engstart').value;
        let speed = parseInt(num);

        let car = new Vehicle(pickColor, 0 , speed);


        function startEngine()
        {
            alert(car.engineOn());
            document.getElementById('displays').innerHTML += car.show() + "<br>";
        }

        function accel()
        {
            alert(car.accelerate());
            document.getElementById('displays').innerHTML += car.accelerate();
        }

        function carInBrake()
        {

            alert(car.brake());

        }


    </script>
</div>


</body>

</html>

And here's the external JS file:

class Vehicle{
    constructor(color, direction, currentSpeed, topSpeed, engineStarted){
        this._color = color;
        this._direction = direction;
        this._currentSpeed = currentSpeed;
        this._topSpeed = 300;
        this._engineStarted = true;
    }

    engineOn() {

        this._engineStarted = true;
        const started = `${this._color} car engine has started (VROOM VROOM!!!)`;
        return started;
    }

    show() {

            if(this._engineStarted)
            {
                const start = `Starting Speed: ${this._currentSpeed} mph<br/>
                                Direction: ${this._direction}º `;
                return start; 
            }
    }

    brake() {

        this._engineStarted = false;
        const message = "Car In Brake";
        return message;
    }

    accelerate() {

        if(this._engineStarted)
        {
            this._currentSpeed + 10;
            const current = `Accelerating. Current speed is now ${this._currentSpeed} mph.`;

        return current;
        }

    }

    left() {

        let dir = this._direction;
        let turn = dir - 10;
        return `Turning left. direction is now ${turn} degrees`;

        let newTurn = turn - 10;

        let this._direction = newTurn;

    }

    }

}

In order to access the class Vehicle in another js file, you first need to export the class and then import in your js file.

script.js

import { Vehicle } from './vehicle.js';

let pickColor = prompt("Pick a color");
//let num = prompt("Pick your starting speed in mph");
let num = document.getElementById('engstart').value;
let speed = parseInt(num);

let car = new Vehicle(pickColor, 0, speed);

window.startEngine =function() {
  alert(car.engineOn());
  document.getElementById('displays').innerHTML += car.show() + "<br>";
}

window.accel = function() {
  alert(car.accelerate());
  document.getElementById('displays').innerHTML += car.accelerate();
}

window.carInBrake = function () {
  alert(car.brake());
}

vehicle.js

export class Vehicle {
  constructor(color, direction, currentSpeed, topSpeed, engineStarted) {
    this._color = color;
    this._direction = direction;
    this._currentSpeed = currentSpeed;
    this._topSpeed = 300;
    this._engineStarted = true;
  }

  engineOn() {
    this._engineStarted = true;
    const started = `${this._color} car engine has started (VROOM VROOM!!!)`;
    return started;
  }

  show() {
    if (this._engineStarted) {
      const start = `Starting Speed: ${this._currentSpeed} mph<br/>
                                Direction: ${this._direction}º `;
      return start;
    }
  }

  brake() {
    this._engineStarted = false;
    const message = "Car In Brake";
    return message;
  }

  accelerate() {
    if (this._engineStarted) {
      this._currentSpeed + 10;
      const current = `Accelerating. Current speed is now ${this._currentSpeed} mph.`;
      return current;
    }
  }

  left() {
    let dir = this._direction;
    let turn = dir - 10;
    return `Turning left. direction is now ${turn} degrees`;
  }
}

index.html

<div id="input">
    <br />
    <br />
    <br />
    <input type="text" id="engstart"> Pick Your Starting Speed</input>
    <br />
    <button onclick="startEngine()"> Start the Car </button>
    <br />
    <br />
    <button onclick="accel()"> Accelerate </button>
    <br>
    <br />
    <button onclick="carInBrake()"> Put Car In Brake </button>
    <br />
    <br />
    <button onclick="left()"> Turn Left </button>
  </div>
  <div id="displays"></div>

  <script type="module" src="./script.js"></script>

The problem is the last statement in left() method. Since this._direction is the class variable and is already defined, you shouldn't be using the let keyword there. Just change-

let this._direction = newTurn;

to

this._direction = newTurn;

As pointed out by Patrick, the return statement should also be written at the end of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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