简体   繁体   English

使用javascript或php将相同的类添加到动态创建的元素中

[英]adding same class to dynamic created elements with javascript or php

Hello! 你好!

So for each category in an online shop i have a page with every subcategory included and a table with products. 因此,对于在线商店中的每个类别,我都有一个包含每个子类别的页面和一个包含产品的表格。 I have this table with sorting buttons on top for each subcategory of products. 我有此表 ,在每个产品子类别的顶部都有排序按钮。 What I want is to put the same color as the buttons to each row(product) in the table. 我想要的是将与按钮相同的颜色放置到表中的每一行(产品)。 So where the product is from the Display subcategory the color should be green and so on. 因此,如果产品来自“显示”子类别,则颜色应为绿色,依此类推。

This needs to be done dynamically because I have more pages like that, created from the database. 这需要动态完成,因为我有更多类似的页面是从数据库创建的。 Another page 另一页

To add the subcategory colors I'm using a simple 要添加子类别颜色,我使用了一个简单的

$class++

in the while loop. 在while循环中。 with css classes created like 使用创建的CSS类

.col1{
   color: #3e8f3e;
}
.col2{
   color: #e38d13;
}
.col3{
   color: #b92c28;
}
.col4{
   color: #DC4C46;
}
.col5{
   color: #672E3B;
}
.col6{
   color: #F3D6E4;
}
.col7{
   color: #C48F65;
}
.col8{
   color: #223A5E;
}
.col9{
   color: #898E8C;
}
.col10{
   color: #005960;
}
.col11{
   color: #9C9A40;
}
.col12{
   color: #4F84C4;
}

I used the subcatergory name as the id of the button. 我使用子类别名称作为按钮的ID。 Code for button: 按钮代码:

<li>
    <a type="button" class="btn-filter" id="'.$row['subcat_pro'].'" href="#go" title="'.$row['subcat_pro'].'" data-target="'.$row['subcat_pro'].'">'.$row['subcat_pro'].'</a><hr class="btn'.$class++.'">
</li>';

Code for the <span> where the color should be: <span>代码,其中颜色应为:

<span id="sub'.$row['subcat_pro'] .'" class="pull-right">('. $row['subcat_pro'] .') (SKU: '. $row['sku'] .')</span>

I really have no idea of what can be done. 我真的不知道该怎么办。

Thanks in advance for any help! 在此先感谢您的帮助!

honestly, i would put that color IN your "categories" or "subcategories" table, like, i would create a colunm called "color" and then when you are creating your table you could do something like this: 老实说,我会将该颜色放入您的“类别”或“子类别”表中,例如,我将创建一个名为“ color”的库,然后在创建表时可以执行以下操作:

<?php 
    $categories = $db ... // get your categories here using a query

    foreach($categories as $category) {
          <span name="category_{$category['id']}" style="color:{$category['color']}" ><span>
    }
?>

But, if you don't like styles in-line on your HTML, like i don't, you will have to define all those colors as classes on your CSS file, then, you would build that html using those classes. 但是,如果您不喜欢HTML上的内联样式(如我不喜欢),则必须将所有这些颜色定义为CSS文件上的类,然后,您将使用这些类来构建该html。

Let me know if you want a example for the second option (which is pretty hard work). 让我知道您是否想要第二个选项的示例(这是非常艰苦的工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM