代码之家  ›  专栏  ›  技术社区  ›  janhartmann

在表格行中查找类

  •  1
  • janhartmann  · 技术社区  · 15 年前

    看看这张桌子:

    <table cellpadding="0" cellspacing="0" class="order_form">
        <tr>
            <th>Amount</th>
            <th>Desc</th>
            <th>Price</th>
            <th>Total</th>
        </tr>
        <tr>
            <td><input type="text" class="order_count" /></td>
            <td>
                <span class="order_desc">Middagstallerken</span>
            </td>
            <td>
                <span class="order_price">1,15</span>
            </td>
            <td>
                <span class="order_each_total"></span>
            </td>
        </tr>
        [...]
    </table>
    

    输入金额后,我需要选择“订单价格”类,并将其与输入的“订单数量”值相乘,然后将其置于“订单数量”中。我有很多这样的行,所以我需要在行中找到下一个类。

    我尝试过使用这样的函数,但没有结果:

    <script type="text/javascript">
        $(document).ready(function(){
            $('.order_count').keyup(function() {
                var each_price = $(this).prevUntil("tr").find("span.order_price").text();
            });
         });
    </script>
    

    我希望有人能找到一个好的解决办法——)

    1 回复  |  直到 8 年前
        1
  •  2
  •   Tatu Ulmanen    15 年前

    使用 closest() 而不是 prevUntil :

    $(document).ready(function(){
        $('.order_count').keyup(function() {
            var amount = parseInt($(this).val(), 10);
            var each_price = $(this)
                                 .closest('tr')
                                 .find('span.order_price')
                                 .text()
                                 .replace(',', '.'); // Floats use . as separator
    
            each_price  = parseFloat(each_price);
            total_price = amount * each_price;
    
            // Update the value
            $(this)
                .closest('tr')
                .find('span.order_each_total')
                .text(total_price
                    .toFixed(2) // "Round" to two decimal places
                    .replace('.', ',') // Format properly
                );
        });
     });
    

    记住使用 parseFloat parseInt 当试图在计算中使用来自dom的数字时,它们是字符串作为默认值。