Jquery 按钮返回未定义

Just_some_Noob

我正在尝试使用 jquery 按钮(单击时)将参数推送到数组中,但控制台返回“未定义”。不确定为什么没有引用输入值。这是我的代码..

//JAVASCRIPT

let garage = [];

class Car{
  constructor( year, make, model ){
    this.year = year;
    this.make = make;
    this.model = model;
  } //end constructor
} // end Car class
let newCar = new Car( $( '#yearIn' ).val(), $( '#makeIn' ).val(), $( '#modelIn' ).val() );
$( document ).ready( function () {
 $('#submitCarButton').on('click', function(){
   //console.log( $('#yearIn').val(this.year) );
    garage.push(newCar);
    console.log(garage);

 }); //end enterButton on click
}); //end document ready//


//HTML
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="jquery-3.3.1.min.js" charset="utf-8"></script>
    <link rel="stylesheet" href="styles.css">
    <script src="client.js" charset="utf-8"></script>
     <title>Week 6</title>
  </head>
  <body>
    <h1>Garage Inventory</h1>
    <div id="garageDiv">

    </div>
    <p1>Enter car here</p1>
    <div id="carInput">
      <input type="text" placeholder="Year" id"yearIn" />
      <input type="text" placeholder="Make" id"makeIn"/>
      <input type="text" placeholder="Model" id"modelIn" />
      <button id='submitCarButton'>Add Car</button>
    </div>

    <h2>Cars In the Garage</h2>
  </body>
</html>

有一次我得到它说'#makeIn,'#yearIn 等......

沙伊·阿哈罗尼

那么你有几件事需要修复:

首先,您在 id 属性中缺少 '=' 符号:(id"yearIn" 应该是 id="yearIn")

<input type="text" placeholder="Year" id="yearIn" />
  <input type="text" placeholder="Make" id="makeIn"/>
  <input type="text" placeholder="Model" id="modelIn" />

其次,需要在click事件中实例化newCar实例,这样每次点击add时,都会添加一个新的实例。

 $('#submitCarButton').on('click', function(){
   let newCar = new Car( $('#yearIn').val(), $('#makeIn').val(), $( '#modelIn' ).val() );
    garage.push(newCar);
    console.log(garage);

 }); //end enterButton on click

看看这个小提琴:https : //jsfiddle.net/b69xvozt/13/

希望这可以帮助 :)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章