2010-01-30 18 views
7

我正在做一家書店,想添加一個花哨的jQuery訂單。重點是用戶應該選擇一個帶有減號和加號按鈕的書的數量,然後讓JavaScript計算該書的總和。查找當前表格行中的輸入字段

我有一個標記如下:

<tr> 
    <td><p>Book title</p></td> 
    <td><p><a href="#" class="bookDecrement">-</a><input type="text" class="bookQuantity disabled" disabled /><a href="#" class="bookIncrement">+</a></p></td> 
    <td><p><input type="text" class="bookPrice disabled" value="70" disabled /></p></td> 
    <td><p>=</p></td> 
    <td><p><input type="text" class="bookTotal disabled" disabled /></p></td> 
    </tr> 

如何此行與jQuery在到達bookPrice和bookTotal類?由於我有多個書名,我只需要訪問當前行中的輸入字段。

謝謝!

回答

23

這應做到:

$('.bookDecrement, .bookIncrement').click(function() { 

    // Get the current row 
    var row = $(this).closest('tr'); 

    // Determine if we're adding or removing 
    var increment = $(this).hasClass('bookDecrement') ? -1 : 1; 

    // Get the current quantity 
    var quantity = parseInt(row.find('.bookQuantity').val(), 10); 
    // Adjust the quantity 
    quantity += increment; 
    // Quantity must be at least 0 
    quantity = quantity < 0 ? 0 : quantity; 

    // Get the price 
    var price = parseFloat(row.find('.bookPrice').val()); 

    // Adjust the total 
    row.find('.bookTotal').val(quantity * price); 

    // Return false to prevent the link from redirecting to '#' 
    return false; 
}); 
+0

哦非常感謝!我真的不需要你爲我寫完整件事,但我不介意:)!再次感謝很多 – 2010-01-30 21:27:30

13

你可以得到祖先tr和再次下降到內的輸入。像這樣:

$("a.bookIncrement").click(function() { 
    $(this).closest("tr").find("input.bookPrice").doSomething(); 
}); 
+0

不錯的一個!謝謝! – 2010-01-30 21:24:54

相關問題