我正在一個電子商務網站上工作,產品正在使用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>
不要在多個元素上使用相同的「id」屬性。改用「class」。 – hindmost
價格是所有'.choose'值的總和,還是僅僅是已更改的選擇框的值?另外,你使用的是什麼版本的jQuery? – tftd