将类添加到一组动态创建的div的第一个div中 [英] Appending a class to the first div of a set of dynamically created divs

查看:120
本文介绍了将类添加到一组动态创建的div的第一个div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一种情况,我需要在一组动态创建的div中附加一个名为"active" 的类.我的问题是我想只将"active"类添加到动态创建的div集的第一个中,而其余部分则没有.

I run in to a situation where I need to append a class called "active" in to a set of dynamically created divs. My issue is that I am suppose to only add the class "active" to the very first of the dynamically created div set and rest not have it.

这是我的html示例.

Here is my html example.

 <!-- Begin Carousel -->   
 <div id="carousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <li data-target="#carousel" data-slide-to="0" class="active"></li>
        <li data-target="#carousel" data-slide-to="1" class=""></li>
        <li data-target="#carousel" data-slide-to="2" class=""></li>
    </ol>

    <!-- Wrapper for slides -->
    <div id="CAROUSEL_CONTENTHERE" class="carousel-inner">

        <!-- DYNAMICALLY CREATED DIVS GO HERE -->

    </div>
 </div>

这是动态创建的DIV的样子

Here is what the dynamically created DIVs look like

        <div class="item bgwhite"> <!-- class active should append here. -->
            <div class="carousel-img-full">
                <a href="#"><img src="img/banner2.jpg" alt=""></a>
            </div>
        </div>

所以本质上我想

        <div class="item bgwhite active"> 
            <div class="carousel-img-full">
                <a href="#"><img src="img/banner1.jpg" alt=""></a>
            </div>
        </div>
        <div class="item bgwhite">
            <div class="carousel-img-full">
                <a href="#"><img src="img/banner2.jpg" alt=""></a>
            </div>
        </div>
        <div class="item bgwhite">
            <div class="carousel-img-full">
                <a href="#"><img src="img/banner3.jpg" alt=""></a>
            </div>
        </div>

有什么想法可以使用jquery来实现吗?感谢您抽出宝贵的时间阅读这篇文章.

Any idea how I can approach this using jquery? Thank you for taking your time to read this.

推荐答案

在添加div之后,您可以使用

After appending your div, you can use .first() to get the first div with class item and bgwhite, then add class active to it using .addClass():

将匹配元素的集合减少到集合中的第一个.

Reduce the set of matched elements to the first in the set.

$('.item.bgwhite').first().addClass('active');

这篇关于将类添加到一组动态创建的div的第一个div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆