在用户输入后尝试操作类信息

问题描述 投票:0回答:2

我基本上是试图学习如何接受用户输入并根据我已经设置的班级信息显示输入。换句话说,我希望用户的输入成为从类信息生成的字符串的一部分。我目前在浏览器中获得了字符串,但是当我按下按钮时,得到的是“空”而不是用户输入。有人可以告诉我我在做什么错吗?

class Vehicle{
//Set up object
  constructor(color, direction, currentSpeed, topSpeed, engineStarted){
    this._color = color;
    this._direction = direction;
    this._currentSpeed = currentSpeed;
    this._topSpeed = topSpeed;
    this._engineStarted = true;
  }
						
  accelerate(){
    return `Car is now travelling @ ${this._currentSpeed} mph.`;
  }
}

let input = document.getElementById('input1');
let myCar2 = new Vehicle("Green", 233, input, 90);
function whatsTheSpeed() {
  document.getElementById('display').innerHTML +=  myCar2.accelerate();
}
<div id="info">
  <input type="text" id="input1">
  <button onclick="whatsTheSpeed()">Speed</button>
</div>
<div id="display"></div>
javascript string class object input
2个回答
0
投票

尝试使用input.value,而不只是input

let input = document.getElementById('input1').value;

0
投票

input变量选择<input>元素。但是由于得到的结果是null,这可能意味着您的脚本是在您尝试选择的HTML之前执行的。确保首先拥有HTML元素,并在页面底部具有此脚本的<script>标签。

然后,当document.getElementById('input1');确实为您提供元素时,请使用该元素的value属性来获取输入中的当前value

如果您希望您的汽车每次单击都更新速度,则需要在whatsTheSpeed功能中更新您的实例。

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

  setSpeed(speed) {
    this._currentSpeed = speed;
  }
						
  accelerate(){
    return `Car is now travelling @ ${this._currentSpeed} mph.`;
  }
}

let input = document.getElementById('input1');
let myCar2 = new Vehicle("Green", 233, input.value, 90);

function whatsTheSpeed() {
  myCar2.setSpeed(input.value);
  document.getElementById('display').innerHTML =  myCar2.accelerate();
}
<div id="info">
  <input type="text" id="input1">
  <button onclick="whatsTheSpeed()">Speed</button>
</div>
<div id="display"></div>

0
投票

class Vehicle{
//Set up object
  constructor(color, direction, currentSpeed, topSpeed, engineStarted){
    this._color = color;
    this._direction = direction;
    this._currentSpeed = currentSpeed;
    this._topSpeed = topSpeed;
    this._engineStarted = true;
  }
						
  accelerate(){
     let input = document.getElementById('input1').value;
    return 'Car is now travelling @ ' + input + ' mph.';
  }
}


let myCar2 = new Vehicle("Green", 233, 20, 90);
function whatsTheSpeed() {
  document.getElementById('display').innerHTML +=  myCar2.accelerate();
}
<div id="info">
  <input type="text" id="input1">
  <button onclick="whatsTheSpeed()">Speed</button>
</div>
<div id="display"></div>
© www.soinside.com 2019 - 2024. All rights reserved.