我的代码如下所示:
.wrapper {
width: 140px;
}
.box {
position: relative;
display: block;
width: 100%;
border: 1px solid #e3e3e3;
border-radius: 4px;
overflow: hidden;
}
.box_top {
position: relative;
display: block;
background-color: #fff;
min-height: 70px;
}
.box_top img {
max-width: 100%;
height: auto;
display: block;
padding: 0;
margin: 0;
}
.box_content {
position: relative;
display: block;
box-sizing: border-box;
width: 100%: padding: 5px 15px;
background-color: #f4f4f4;
}
.box_title,
.box_description,
.price,
.button {
position: relative;
display: block;
text-align: center;
padding: 5px;
margin: 0;
}
.box_title {
font-size: 18px;
}
.button {
line-height: 20px;
color: #fff;
background-color: #333;
cursor: pointer;
}
<div class="wrapper">
<div class="box" id="product_1">
<div class="box_top">
<img src="http://oregonaitc.org/wp-content/uploads/2016/02/potato.jpg" alt="Product 1" />
</div>
<div class="box_content">
<a class="box_title">TITLE</a>
<p class="box_description">
Description
</p>
<a class="price">$10</a>
<a class="button" id="product_1_add">
Add to cart
</a>
</div>
</div>
</div>
我想要做的是为每个元素添加一个唯一的ID,以便稍后可以使用jQuery单独定位每个框。
有点像<div class="box" id="product_1">
,<div class="box" id="product_2">
等等。
问题是在我的页面上有很多像这样的产品盒,并且需要花费很多时间手动为每个元素添加一个唯一的id。我如何使用jQuery或PHP来解决这个问题?
答案 0 :(得分:0)
只需循环浏览所有产品并将其回显即可
我做了以下假设:
1.直接从数据库中提取
2.拉力是2D阵列的形式
3.来自该数据的密钥是&#34;图像&#34;,&#34;标题&#34;,&#34;描述&#34;和&#34;价格&#34;
<?php
$productArray = array(); //The array of your product data
for ($i=1; $i=<count($productArray); i++;){
echo '<div class="wrapper">
<div class="box" id="product_'.$i.'">
<div class="box_top">
<img src="http://oregonaitc.org/wp-content/uploads/2016/02/'.$productArray[$i-1]['Image'].'" alt="Product '.$i.'" />
</div>
<div class="box_content">
<a class="box_title">'.$productArray[$i-1]['Title'].'</a>
<p class="box_description">
'.$productArray[$i-1]['Description'].'
</p>
<a class="price">'.$productArray[$i-1]['Price'].'</a>
<a class="button" id="product_'.$i.'_add">
Add to cart
</a>
</div>
</div>
</div>';
}
?>
答案 1 :(得分:0)
如果你想使用jQuery添加ID
$([selector_to_your_divs]).each(function(index) {
$(this).attr("id","id_prefix_"+index);
});