2014-01-26 68 views
1

我正在一個電子商務網站上工作,產品正在使用foreach循環動態生成,每個產品中都有產品選項,當選擇產品選項時我的預期行爲是針對價格更新。jQuery + PHP動態創建的內容

我有這個工作,但jQuery更新頁面上的價格的每個實例和選擇選項只適用於生成的第一個項目。如何將jQuery添加/綁定到對象/每個產品,並根據個人基礎改變價格?

<?php 
    foreach($items as $item): 
    <?php echo $the_name ?> 

    <select id="choose"> 
     foreach($selection as $select): 
     <option value="$some_var" data-value="$the_price">$some_var</option> 
     endforeach; 
    </select> 

    <div id="price"><?php echo $the_price ?></div> 
    endforeach; 
?> 

<script type="text/javascript"> 
    jQuery('#choose').change(function (event) { 
    jQuery('#price').html(jQuery('#choose option:selected').data('value')); 
    }).change(); 
</script> 

工作守則

打約了一段時間,並考慮到以下的其他意見後,此代碼的工作。

<script type="text/javascript"> 
    jQuery('.choose').change(function (event) { 
    var $t = jQuery(this); 
    var price = $t.find('option:selected').data('value'); 
    $t.parents('form').find('.price').html(price); 
    }).change(); 
</script> 
+0

不要在多個元素上使用相同的「id」屬性。改用「class」。 – hindmost

+0

價格是所有'.choose'值的總和,還是僅僅是已更改的選擇框的值?另外,你使用的是什麼版本的jQuery? – tftd

回答

1

的ID都是唯一的。因爲「選擇」處於循環狀態,所以您有多個選擇ID,這不會有所幫助。與'價格'一樣。所以,讓我們改變了一點:

<?php 
    foreach($items as $item): 
     <?php echo $the_name ?> 
     <select class="choose"> 
      foreach($selection as $select): 
      <option value="$some_var" data-value="$the_price">$some_var</option> 
      endforeach; 
     </select> 
     <div class="price"><?php echo $the_price ?></div> 
    endforeach; 
?> 
<script type="text/javascript"> 
    jQuery('.choose').change(function (event) { 
     jQuery(this).next().html(jQuery(this).data('value')); 
    }).change(); 
</script> 

說明:

既然你可以有一個以上的choose,然後需要做一些DOM導航拿到price,是相對於選擇。因此,無論何時選擇框被更改,它都會在DOM樹中查找next元素,這是一個兄弟元素,如果您的代碼片段已完成,則元素爲price,然後將html更新爲該值。一個想法雖然 - 你可能想要使用text而不是html,除非你的價格中有HTML。另外,當你在事件中時(除非你做了一些特殊的事情來重新綁定範圍),在jQuery this中將引用事件觸發的元素。因此,jQuery(this)將返回一個jQuery引用到已更改的元素。

+0

根據OP給出的內容,它應該是更改後的選擇框的值。 – Stephen

+0

Ahh ..對不起,我雖然是在評論OP的問題...忽略我的評論 – tftd

+0

感謝您的答案,非常thourugh,並幫助我瞭解操縱DOM – iamgraeme

0
<?php 

     foreach($items as $item): 

     <?php echo $the_name ?> 

     <select class="choose"> 
     foreach($selection as $select): 

     <option value="$some_var" data-value="$the_price">$some_var</option> 

     endforeach; 
     </select> 

     <div class="price"><?php echo $the_price ?></div> 

     endforeach; 



    ?> 
    <script type="text/javascript"> 
     jQuery('.choose').change(function (event) { 
     jQuery$(this).parent().next(".price").html(jQuery('#choose option:selected').data('value')); 
     }).change(); 
    </script>