2010-03-08 15 views
1

看看這個表:在錶行查找類

<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> 

一旦進入量,我需要選擇班級「order_price」,並輸入「ORDER_COUNT」的值相乘,並把它放在「order_each_count」。我有很多這樣的行,所以我需要找到行中的下一個類。

我一直在使用一些功能像這樣的,但沒有結果的嘗試:

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

我希望有人有:-)

+0

你的'keyup'函數被調用了嗎? – 2010-03-08 09:52:11

+0

您確定要在客戶端上執行此操作嗎?在生成表格時,您可以在服務器上進行這些計算嗎?你真的擁有數百萬行嗎? – Douglas 2010-03-08 09:55:59

+0

不,不是數百萬,更像40 :-)對不起,使用數百萬,嘿嘿。 – janhartmann 2010-03-08 09:56:33

回答

2

使用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 
      ); 
    }); 
}); 

請記住在嘗試使用DOM中的數字計算–時使用parseFloatparseInt '作爲默認字符串。

+0

非常好:-)除了替換功能外,它像一個魅力一樣。它不被承認。 – janhartmann 2010-03-08 10:01:27

+0

你應該傳遞一個基數到parseInt,除非你想要猜測它。例如,parseInt($(this).val(),10)。 https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Functions/ParseInt – Douglas 2010-03-08 10:03:15

+0

修復替換通過切換.toFixed和.replace :-) – janhartmann 2010-03-08 10:14:47