2014-07-16 35 views
1

我試圖實現的是從頁面獲取所有產品的名稱,並將其存儲在比我可以在代碼的下一部分中使用的數組中。這裏是我迄今需要在jQuery中傳遞關聯數組中的值

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">  </script> 
<script type="text/javascript"> 
jQuery(document).ready(function($) { 
var i = 1; 
$(".product-name").each(function() { 
    var pnameforostock = $(this).text(); 
    var positionp = i++; 
        alert(pnameforostock); 

    }); 

    }); 
</script>  
<body> 
<li class="item"> 

      <a href="product1.php" title="Sample Product Name" class="product-image"> 
           <span class="sale-item">Sale!</span> 
           <div class="cat-mouseover"></div> 
       <img src="/images/product1.png" alt="Sample Product Name"></a> 
      <h2 class="product-name"><a href="product1.php" title="Sample Product Name">Sample Product Name</a></h2> 
<div class="price-box"> 

       <p class="old-price"> 
      <span class="price-label">For:</span> 
      <span class="price" id="old-price-426"> 
       &nbsp;199,-    </span> 
     </p> 

        <p class="special-price"> 
      <span class="price-label"></span> 
      <span class="price" id="product-price-426"> 
       Now&nbsp;139,-    </span> 
     </p> 


    </div> 
          <div class="actions"> 
             <button type="button" title="Buy Now" class="button btn-cart" onclick="setLocation('http://www.google.com/')"><span><span>Buy</span></span></button>  
           </div> 
     </li> 

<li class="item"> 

      <a href="product1.php" title="Sample Product Name" class="product-image"> 
           <span class="sale-item">Sale!</span> 
           <div class="cat-mouseover"></div> 
       <img src="/images/product1.png" alt="Sample Product Name"></a> 
      <h2 class="product-name"><a href="product1.php" title="Sample Product Name">Sample Product Name 2</a></h2> 
<div class="price-box"> 

       <p class="old-price"> 
      <span class="price-label">For:</span> 
      <span class="price" id="old-price-426"> 
       &nbsp;199,-    </span> 
     </p> 

        <p class="special-price"> 
      <span class="price-label"></span> 
      <span class="price" id="product-price-426"> 
       Now&nbsp;139,-    </span> 
     </p> 


    </div> 

          <div class="actions"> 
             <button type="button" title="Buy Now" class="button btn-cart" onclick="setLocation('/checkout/cart/add/uenc/aHR0cDovL3d3dy52aXRhLm5vLw,,/product/426/')"><span><span>Buy</span></span></button> 
           </div> 
     </li> 

     </body> 
</html> 

完成從上面的jQuery代碼我能夠拿到的產品名稱,但不能將它們放置在陣列,使其看起來像這樣

名:product1,name:product2

我試了很多在數組中獲得一些結果,但沒有成功。請指教。

回答

0

你希望的對象數組(JS沒有關聯數組)

var products = $(".product-name a").map(function() { 
    return { name: $(this).text() } 
}).get(); 

.map參考:http://api.jquery.com/jquery.map/

+0

謝謝@tymeJV的代碼,但我不能夠得到從這個代碼輸出。我取代了我的jquery代碼,但沒有成功。你可以請指導。 – user3550203