我想要实现的是从页面获取所有产品名称,而不是将其存储在一个数组中,而不是我可以在下一部分代码中使用。这是我到目前为止所做的
<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">
199,- </span>
</p>
<p class="special-price">
<span class="price-label"></span>
<span class="price" id="product-price-426">
Now 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">
199,- </span>
</p>
<p class="special-price">
<span class="price-label"></span>
<span class="price" id="product-price-426">
Now 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代码中我可以获得产品名称,但无法将它们放在数组中,以便它看起来像这样
name:product1,name:product2
我尝试了很多在阵列中得到一些结果但没有成功。请指教。
答案 0 :(得分:0)
你想要一个对象数组(JS没有关联数组)
var products = $(".product-name a").map(function() {
return { name: $(this).text() }
}).get();