簡體   English   中英

jQuery + PHP動態創建的內容

[英]jQuery + PHP Dynamically Created Content

我在一個電子商務網站上工作,並且產品通過foreach循環動態生成,每個產品中都有產品選項,當選擇了產品選項時,我的預期行為是更新價格。

我已經完成了這項工作,但是jQuery正在更新頁面上價格的每個實例,而select選項僅適用於生成的第一個項目。 如何將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是唯一的。 因為“選擇”是一個循環,所以您有多個選擇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樹中尋找同級的下一個元素,如果您的代碼段完整,則為price元素,然后將html更新為該值。 不過,請三思而后行-您可能希望使用文本而不是html ,除非價格中包含HTML。 另外,當您處於事件內部時(除非您做了一些特殊的操作以重新綁定作用域),在jQuery中, this將引用事件觸發的元素。 因此, jQuery(this)將返回對已更改元素的jQuery引用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM