2017-07-03 64 views
0

我想創建一個網上商店,我用單選按鈕中的Jquery選擇一個類別,但輸出始終只在第一個項目上,而不是在每個項目中。jquery-輸出總是隻在第一個項目

這裏是jQuery代碼

function populateswatches() { 

     var swatchesName = $('input[name=optradio]:checked').val(); 

     $.getJSON('getdata.php', {swatchesName: swatchesName}, function(swatch) { 

      var html = ''; 
      $.each(swatch, function(index, array) { 
       html = html + '<div class="col-md-3 w3-margin-top"><div class="w3-display-container w3-hover-opacity"><div class="w3-center"><input type="radio" name="swatches_code" value="' + array['swatches_code'] + '" required></div><div class="w3-display-middle w3-display-hover"><a href="../backend/functions/images/'+array['images']+'" target="_blank"><button type="button" class="btn btn-primary"><i class="fa fa-search fa-lg" aria-hidden="true"></i></button></a></div><img src="../backend/functions/images/'+array['images']+'" style="width:100%"><div class="w3-center">' + array['swatches_code']+'</div></div></div>'; 
      }); 
      $('#swatches').html(html); 
     }); 
    } 

    $(function() { 
     $(this).change(function() { 
      populateswatches(); 
     }); 
    }); 

這裏是PHP代碼。但它並不完整。

$priceSQL="SELECT * FROM price WHERE id_item='$IDitem'"; 
     $priceRES=mysqli_query($conn,$priceSQL); 
     while($priceROW=mysqli_fetch_assoc($priceRES)){ 
      $id_categ=$priceROW["id_category"]; 

      $catSQL="SELECT * FROM category WHERE id_category='$id_categ'"; 
      $catRES=mysqli_query($conn,$catSQL); 
      while($catROW=mysqli_fetch_assoc($catRES)){ 
      echo ' 
       <div class="radio"> 
        <label><input type="radio" name="optradio" value="'.$priceROW["price"].'-'.$id_categ.'" required>'.$catROW["swatches_category"].'- &#8369;'.formatMoney($priceROW["price"]).'</label> 
       </div> 
      '; 
      } 
     }     
      </li> 
     </ul> 
      <h4>SWATCHES</h4> 
      <div class="form-group"> 
       <span id="swatches"></span> 
      </div> 
      <input type="hidden" value="'.$IDitem.'" name="id_item">   
     </div> 
    </div> 
    </div> 
    <div class="modal-footer"> 
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
    <button type="submit" class="btn btn-success">Add to Cart</button> 

這裏是輸出 here is the image output for it

+2

請提供您的實際代碼而不是圖片。 –

+0

這是因爲您爲每個「span」使用了相同的「id」。所以這就是爲什麼它只爲第一個工作。將'id'轉換爲'class'.BTW總是分享你的實際代碼而不是圖片,因爲很難識別圖像中的問題(非常耗時,並且沒有人有興趣檢查圖像,並嘗試找出錯誤) –

回答

0

原因: -

id被視爲unique identifierjQuery。由於所有spans在你的代碼有相同id,這就是爲什麼只有代碼爲第一個工作。

解決方案: -

轉換idclass在你的HTML代碼象下面這樣: -

<span class="swatches"></span>

而在jQuery的改變#.象下面這樣: -

$('.swatches').html(html); 

注意: -class在jQuery中被視爲group identifier,並在共享相同類的每個元素上工作。

+0

謝謝,它工程兄弟,但還有另一個問題。當我選擇第二個項目,那麼它的輸出仍然在第一個項目上,我不能改變它。 –

+0

@ClifordChing我沒有得到你。你可以問你一個新問題,以便你能夠快速得到答案。請用正確的代碼輸入問一個很好描述的問題(最好,如果你能爲你的問題創建一個小提琴示例)謝謝 –

+0

感謝兄弟我爲新問題創建了新帖子。這裏是鏈接。任何人也需要這個參考這裏是鏈接https://stackoverflow.com/questions/44879927/jquery-the-first-one-to-click-will-bound-on-all-the-items –

相關問題