【问题标题】:Trying to manipulate class info after input from the user在用户输入后尝试操作类信息
【发布时间】:2020-02-13 23:01:42
【问题描述】:
我基本上是在尝试学习如何接受用户输入并根据我已经设置的课程信息显示输入。换句话说,我希望用户的输入成为从类信息生成的字符串的一部分。我目前在浏览器中获取字符串,但是当我点击按钮时我得到“null”而不是用户输入。谁能告诉我我做错了什么?
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
【解决方案1】:
尝试使用input.value 而不仅仅是input
let input = document.getElementById('input1').value;
【解决方案2】:
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>
【解决方案3】:
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>