javascript - 为什么我不能使用 jquery id 值调用函数?

标签 javascript jquery html

我有一些简单的 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/

相关文章:

javascript - 吉森忽视了我的一条规则

javascript - 如何在 Leaflet 中将点从 [x,y] 坐标投影到 LatLng?

javascript - 如何计算以百分比给出的三者之间的比例颜色?

javascript - 单击子元素时阻止父类

javascript - 无法在 Internet Explorer 上使用 javascript 访问选项值

javascript - 使用三元运算符和递归连接字符串

javascript - 如何在寄存器上触发 Parse.Cloud.afterSave

javascript - 执行完我的一组功能后如何做某事?

jquery - CSS - 动画列表顺序

html - 显示:内联即使使用 float 也不起作用