【问题标题】:Javascript Add Custom active Class inside loopJavascript在循环内添加自定义活动类
【发布时间】:2025-11-24 11:45:02
【问题描述】:

我有两个如下所示的循环,您可以看到并需要将自定义 active-numberHere 类添加到每个具有指定数字的 div 的第一个图像。

例如,如果 div 类编号是 img-4,则将类 active-4 添加到第一个 img 标签。

但是我在代码中存在一些问题,您可以在附图中看到。 在第一个 div 图像中具有正确的类。
但在其他 div 图像中具有额外的活动,如 active-4 active-3 和 ...!

我该如何解决这个问题?

// LOOP Create Image Div 
let numDiv = 5;
for (k = 0; k < numDiv; k++) {

    //Add div area inside Div(products)
    let imgPart = `<div class="img-${k} shoe-part"> </div>`;
    document.querySelector(".products").insertAdjacentHTML("afterbegin", imgPart);
    
    
// LOOP Create Image List Inside Divs 
    let numImg = 3;
    for (j = 0; j < numImg; j++) {
    
        //Add Image List Inside Above Div(shoe-part)
        let imgList = `<img class="res-img" src="img/image-${k}.png">`;
        document.querySelector(".shoe-part").insertAdjacentHTML("afterbegin", imgList);
    }
$('.shoe-part img:first-child').addClass(`active-${k}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="products">

</div>

【问题讨论】:

    标签: javascript jquery html loops


    【解决方案1】:
    • jquery 执行此操作的简单方法是使用html()prepend()append()
    • 对于添加类,您可以在循环中使用简单的 if 语句

    // LOOP Create Image Div 
    let numDiv = 5;
    for (k = 0; k < numDiv; k++) {
    
        //Add div area inside Div(products)
        var DivPart = `<div class="img-${k} shoe-part"></div>`;
        
        
    // LOOP Create Image List Inside Divs 
        let numImg = 3;
        let ImgPart = '';
        for (j = 0; j < numImg; j++) {
            //Add Image List Inside Above Div(shoe-part)
            var AddClass = (j === 0) ? 'active-'+k : ''; // shorthand if statement to add the class only when j = 0
            ImgPart += `<img class="res-img ${AddClass}" src="img/image-${k}.png">`;  // add all the images in the valriable ImgPart by using += it means sum/combine/addto
        }
        DivPart = $(DivPart).html(ImgPart); // update DivPart with the whole div with images in it
        $('.products').prepend(DivPart); // prepend the DivPart to the product div
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="products">
    
    </div>

    【讨论】: