我有一個課堂問題。用戶在輸入字段中輸入三個不同的東西。我們將Materialise和我們自己的site.js文件用於JavaScript和jQuery,但也使用Materialize CSS和JavaScript文件以及jQuery腳本。我可以成功輸入啤酒,種類和價格;該網站將存儲在一個數組和一切。但是當我嘗試通過jQuery用對象創建啤酒時,啤酒顯示爲未定義。追加顯示'undefined'
$('select').material_select();
var beers = [];
var Beer = function(alcohol, style, price) {
this.alcohol = alcohol;
this.style = style;
this.price = price;
};
$("#btnCreateBeer").on("click", function() {
var alcohol = $("#txtName").val();
var style = $("#dboStyle").val();
var price = $("#txtPrice").val();
beers.push(new Beer(alcohol, style, price));
console.log(beers);
$("#tblBeers").append('<tr>' +
'<td>' + beers.alcohol + '</td>' +
'<td>' + beers.style + '</td>' +
'<td>' + beers.price + '</td>' +
'</tr>');
});
<div class="container">
<div class="row">
<div class="col s4">
<div class="input-field">
<input placeholder="Name" id="txtName" type="text">
<label for="txtName">Name</label>
</div>
<div class="input-field">
<select id="dboStyle">
<option value="" disabled selected>Choose your option</option>
<option value="Ale">Ale</option>
<option value="Lager">Lager</option>
<option value="Stout">Stout</option>
<option value="Pilsner">Pilsner</option>
<option value="Porter">Porter</option>
<option value="Wheat">Wheat</option>
</select>
<label>Style</label>
</div>
<div class="input-field">
<input placeholder="Price" id="txtPrice" type="text">
<label for="txtPrice">Price</label>
</div>
<div class="btn" id="btnCreateBeer">Create</div>
</div>
<div class="col s8">
<table>
<thead>
<tr>
<th>Name</th>
<th>Style</th>
<th>Price</th>
<th></th>
</tr>
</thead>
<tbody id="tblBeers"></tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script>
<script type="text/javascript" src="js/materialize.js"></script>
<script type="text/javascript" src="js/site.js"></script>
你正在越來越'未定義',因爲在訪問'array'的值時犯了一個小錯誤,這裏'beers'是一個數組而不是對象。 – itzmukeshy7