我有一些简单的 js 代码,其中包含一个类构造函数、一个空数组和一个采用三个参数并创建对象的函数。我有一个包含 3 个输入部分和一个按钮的 HTML 文件。最后,我尝试使用 jquery 调用 newCar 函数,传递“YearInput”、“MakeInput”和“ModelInput”的用户输入。
我认为应该发生的是,当按下“添加汽车”按钮时,newCar 函数将运行,将用户输入传递到该函数中。
class Car{
constructor( year, make, model ){
this.year = year;
this.make = make;
this.model = model;
} //end constructor
} // end Car class
let garage = [];
function newCar(year,make,model){
console.log( 'in newCar:', year, make, model );
garage.push( new Car( year, make, model ) );
return true;
} // end newCar
这是 HTML:
<input placeholder="year" id='YearInput'/>
<input placeholder="make" id='MakeInput'/>
<input placeholder="model" id='ModelInput'/>
<button id='AddCar'>Add Car</button>
这是 jquery:
$( document ).ready(readyNow);
function readyNow() {$('#AddCar').on('click',newCar($('#YearInput').val(),
$('MakeInput').val(),$('ModelInput').val()))
};
最佳答案
您需要包装 .on
的第二个参数函数内的处理程序。否则,它会在定义后立即执行,而不是单击时执行,这显然是您想要的:
class Car {
constructor(year, make, model) {
this.year = year;
this.make = make;
this.model = model;
} //end constructor
} // end Car class
let garage = [];
function newCar(year, make, model) {
console.log('in newCar:', year, make, model);
garage.push(new Car(year, make, model));
return true;
} // end newCar
$(document).ready(readyNow);
function readyNow() {
$('#AddCar').on('click', function() {
newCar($('#YearInput').val(), $('#MakeInput').val(), $('#ModelInput').val());
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="year" id='YearInput' />
<input placeholder="make" id='MakeInput' />
<input placeholder="model" id='ModelInput' />
<button id='AddCar'>Add Car</button>
还修复了 #MakeInput
和 #ModelInput
的一些错误选择器(#
丢失)。
关于javascript - 为什么我不能使用 jquery id 值调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52524438/