<分区>
标签 javascript php jquery html css
我的代码是这样的:
.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 来解决这个问题?
最佳答案
只需循环遍历所有产品并将它们回显出来。
我做了以下假设:
1. 直接从数据库中提取
2. pull是二维数组的形式
3. 此数据的键是“图片”、“标题”、“描述”和“价格”
<?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>';
}
?>
关于javascript - 有没有办法给每个 div 一个唯一的 id 而不必每次都输入它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39748846/