代码之家  ›  专栏  ›  技术社区  ›  Fred Bergman

使用类查找当前表行中的输入字段

  •  8
  • Fred Bergman  · 技术社区  · 16 年前

    我正在做一个书店,想添加一个花哨的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类?因为我有多个书名,所以我只需要访问当前行中的输入文件。

    谢谢!

    2 回复  |  直到 16 年前
        1
  •  23
  •   Tatu Ulmanen    16 年前

    应该这样做:

    $('.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;
    });
    
        2
  •  13
  •   Chetan S    16 年前

    您可以到达祖先tr并再次下降到其中的输入。这样地:

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