[問題] dynamic table 和jquery

作者: franklee0402 (FrankLee)   2016-08-15 21:36:46
各位前輩好。小弟是學校替代役,暑假在學校當哈登,
負責買飯,最近開始起手寫起這點菜的網站。
先謝謝各位,若有哪邊不合規矩,再麻煩您提醒我一下。謝謝!
http://163.17.177.11/ordering/
我有一個dynamic table 來增加點餐人數。
問題在於我的加減號部分,第一次按下加號時,
我console.log(document.getElementById("qty").value;)
回饋的份量數值不會變,要按下第二次才會變。
(ex: 1,1,2,3,4)
我認為在jquery的.prev()出現問題,但已經卡關好久了,
觀念或邏輯不曉得哪邊出現錯誤?
//HTML 加減號按鈕的部分
<td class="cart_quantity" id="input_div">
<input type='button' value='-' class='qtyminus' field='quantity'
onclick="getPrice()"/>
<input type='text' name='quantity' value='1' id='qty' class='qty'/>
<input type='button' value='+' class='qtyplus' field='quantity'
onclick="getPrice()"/>
</td>
//JS 用來增加點菜人欄位
function addPerson(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
}
//算價格的部分
function getIkegamiPrice(){
var x = document.getElementById("ikegamiID");
var i = x.selectedIndex;
var q = document.getElementById("qty").value;
//數量回報出現問題的地方。如果我連續按加號
//quantity: 1
//quantity: 1
//quantity: 2
//quantity: 3
console.log("quantity: " + q);
var ikegami = [
["招牌飯", 55],
["爌肉飯", 65],
["炸排骨飯", 65],
["滷排骨飯", 65],
["雞排飯", 60],
["土魠魚飯", 65],
["炸雞腿飯", 80],
["蜜汁雞腿飯", 80]
]
var price = ikegami[i-1][1] * q;
document.getElementById("priceCell").innerHTML = price;
}
//jquery
//這是加號按下去時用的jquery部分
$(document).on('click', '.qtyplus', function(e){
e.preventDefault();
var $input = $(this).prev('input');
var currentVal = parseInt($input.val());
if (!isNaN(currentVal)) {
$input.val(currentVal + 1);
} else {
$input.val(0);
}
});
//這是減號
$(document).on('click', '.qtyminus', function(e){
e.preventDefault();
var $input = $(this).next('input');
var currentVal = parseInt($input.val());
if (!isNaN(currentVal) && currentVal > 1 ) {
$input.val(currentVal - 1);
} else {
$input.val(0);
}
});
作者: Hevak (Arthow Eshes)   2016-08-15 22:24:00
你測試的瀏覽器是?我用Chrome 50沒遇到你說的問題喔對不起,原來你說的是function,我沒看清楚,我這邊也有遇到你說的問題其實id這個東西原則上一頁只能有一個同樣的id....所以其實你的寫法還會有加到別欄就會抓錯值的問題
作者: dnzteeqrq (大隻貓)   2016-08-15 23:03:00
先後順序的問題,你每次抓到的值都是上一次的讓getIkegamiPrice()再on('click','.qtyplus')之後執行

Links booklink

Contact Us: admin [ a t ] ucptt.com