2014-07-16 45 views
0

我需要從li元素中獲取名稱和值,並在選擇後顯示它作爲按鈕值,我需要更多的是將該單個值存儲在php var對於後者提交,我走到這一步,但現在我堅持和不斷收到1個尺寸僅爲名稱從一個元素更改爲另一個價值商店

CODE

<button id="changename" class="btn dropdown-toggle size-selector-btn" type="button" data-toggle="dropdown">Select your size <span class="caret" style="display: none;"></span> 
</button> 
    <ul class="dropdown-menu size-list" role="menu"> 
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product); 
         $attributeOptions = array(); 
         foreach ($productAttributeOptions as $productAttribute) { 
          foreach ($productAttribute['values'] as $attribute) { 
           $attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label']; 
          } 
         } 

         $key = "Size"; 
         foreach($attributeOptions[$key] as $size){ ?> 

           <li id="<?php echo $size; ?>" onclick="changeName()"><?php echo $size; ?></li> 
        <?php } 



         } ?> 

        </ul> 
       </div> 
       <script> 
       function changeName() { 
        document.getElementById("changename").innerHTML = "<?php echo $size; ?>"; 
       } 
       </script> 
+1

您的格式設置很糟糕,無法解決發生了什麼問題。 – Steve

+0

它現在更新了,爲混亂sry – user2208907

+0

好吧,以及仍然不是很好,與缺少開放的PHP標籤和不匹配的大括號,但我認爲我有你的問題的要點 – Steve

回答

0

OK,以及有2個問題,我可以看到。首先你的第三個foreach循環看起來應該嵌套在其他循環中,但不是。

第二個問題是您錯誤地理解了php和js的工作方式。在頁面呈現之前,PHP會在服務器上運行,因此js函數中$ size的值將取決於LAST的值。

要解決這個問題,請正確嵌套foreach(當使用php內聯html時,我最好使用塊的模板語法 - 例如if: endif;,foreach: endforeach;以提高可讀性),然後調整js函數以獲取參數,並在onclick事件中傳遞該參數,方法是對點擊的元素進行標記。編號:

<button id="changename" class="btn dropdown-toggle size-selector-btn" type="button" data-toggle="dropdown">Select your size <span class="caret" style="display: none;"></span> 
    </button> 
    <ul class="dropdown-menu size-list" role="menu"> 
     <?php 
     $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product); 
     $attributeOptions = array(); 
     foreach ($productAttributeOptions as $productAttribute) : 
      foreach ($productAttribute['values'] as $attribute) : 
       $attributeOptions[$productAttribute['label']][$attribute['value_index']] = $attribute['store_label']; 
       $key = "Size"; 
       foreach($attributeOptions[$key] as $size):?> 
        <li id="<?php echo $size; ?>" onclick="changeName(this.id);"><?php echo $size; ?></li> 
       <?php endforeach; 
      endforeach; 
     endforeach; 
     ?> 

    </ul> 
</div> 
<script> 
    function changeName(size) { 
     document.getElementById("changename").innerHTML = size; 
    } 
</script> 
+0

好吧這現在的作品,下一個問題是我需要選擇價值從js被添加到$ _product作爲大小,因爲該產品是可配置的,不能被添加到購物車,除非沒有設置大小。 – user2208907

相關問題