我基本上是试图学习如何接受用户输入并根据我已经设置的班级信息显示输入。换句话说,我希望用户的输入成为从类信息生成的字符串的一部分。我目前在浏览器中获得了字符串,但是当我按下按钮时,得到的是“空”而不是用户输入。有人可以告诉我我在做什么错吗?
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>
尝试使用input.value
,而不只是input
let input = document.getElementById('input1').value;
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>
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>