简体   繁体   English

如何将 css 规则添加到 jquery 中动态创建的元素

[英]How can I add a css rule to a dynamically created element in jquery

Is it possible to add css to a specific dynamically created div in jquery?是否可以将 css 添加到 jquery 中特定的动态创建的 div? I want to add an overlay to a specific div but trying to find a way to pass the id from the dynamically created div to the jquery function in order to only add the CSS rule to that specific div, is becoming a task for me.我想向特定 div 添加一个叠加层,但试图找到一种方法将 id 从动态创建的 div 传递到 jquery 函数,以便仅将 CSS 规则添加到该特定 div,这对我来说已成为一项任务。 When I click on the div it adds the overlay to all of them.当我单击 div 时,它会将覆盖添加到所有这些。 Thanks for your time and here is my code.感谢您的时间,这是我的代码。

foreach($selectedPhotoResult as $rowSelect){
    if($counter % 3 === 1){
        echo '</div><div class="row">';
    }
        echo'
        <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer">
            <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'"><div class="price" style="position:absolute;top:0px;;right:15px;z-index:98;height:50px;width:50px;border-radius: 0px 5px 0px 0px;background-image: linear-gradient(to bottom, rgba(0,0,0,0.8) 50%, rgba(0,0,0,0) 100%);"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div></a>
                <div class="well photoControlsMain pht-brd-cl">
                    <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'">
                        <div class="imageOverlayStyle">
                            Something here
                        </div>
                        <figure>                                                        
                           <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt=""/>

                        <div class="photoControlsMainImage">
                            <p style="z-index:9999;">
                        <span class="text-prt-und-bl usernameIndexPos">'.ucwords($row['industryName']).'</span>
                        <span class="adRateIndexPos">$'.$row['ad_rate'].'/hr</span>
         ';

    if($userfile->member_is_loggedin()){    
        echo'<a class="userMsgID" data-toggle="modal" data-target="#msgUserModal" data-userSenduserID-id="'.$rowSelect['user_id'].'" data-userSend-id="'.$rowSelect['industryName'].'" data-username-modal="'.ucwords($rowSelect['industryName']).'"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>';
            if($favList->rowCount() > 0){                                           
                foreach($favListResult as $rowFav){
                    if($rowFav['user_fav_id'] == $user_id){
                            echo'<span class="heartIcoPosRed adUnFav" data-unfav-id="'.$rowFav['fav_id'].'"><a><i class="fa fa-heart heartIcoRedColor"></i></a></span></a>';
                            }                                       
                    }   
            }else{
                echo'<span class="heartIcoPos adFav" data-userFav-id="'.$user_id.'" data-fav-id="'.$row['ad_id'].'"><a class="heartIcoWhite"><i class="fa fa-heart"></i></a></span></a>';
            }   
                echo city($row['ad_city']);
        }else{                                          
            echo'</a>
                <a class="loginDisplayHeader" style="display:none;"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>
                <a class="loginDisplayHeaderFull" id="loginFormShowHeader"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>
                <a class="loginDisplayHeader" style="display:none;"><span class="heartIcoPos heartIcoWhite"><i class="fa fa-heart"></i></span></a>
                <a class="loginDisplayHeaderFull" id="loginFormShowHeader"><span class="heartIcoPos heartIcoWhite"><i class="fa fa-heart"></i></span></a>
                ';

                echo city($row['ad_city']);
                }

            $likes = $conn->prepare("SELECT count(likes) as likeCount
                FROM 
                    likes
                WHERE
                    user_accept_id = :adUserId                                  
                ");
                $likes->bindParam(":adUserId", $adUserId);
                $likes->execute();
                $likesFetch = $likes->fetchAll();                                       
                if($likes->rowCount() > 0){
                    foreach($likesFetch as $rowLikes){

                        echo'<span class="userLikeBtnLG">'.thousandsCurrencyFormat($rowLikes['likeCount']).' Likes <i class="fa fa fa-thumbs-o-up thbsUPND"></i></span>';

                            }
                        }
                    echo'</p>
            </div>
        </figure>
    </div>
 </div>                                             
 '; 
}

Here is the jquery code so far这是到目前为止的jquery代码

   $(".overlayPicHL").on("click", function() {
     const imageOverlayStyle = 
     $(this.nextElementSibling).find('.imageOverlayStyle');
     $(imageOverlayStyle).css({
     backgroundColor: 'yellow'
     });
   });

And this is the CSS for the overlay item这是覆盖项的 CSS

.imageOverlayStyle {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}

It's a simple overlay transition, I just need to figure out how to add this overlay to a specific div that is pulled from the database...dynamically created.这是一个简单的叠加转换,我只需要弄清楚如何将此叠加添加到从数据库中提取的特定 div 中...动态创建。 I have searched for a solution for a while now with no such luck yet.我已经搜索了一段时间的解决方案,但还没有这样的运气。

The .imageOverlayStyle you want to target is a child of the next sibling of the clicked .overlayPicHL , so use nextElementSibling and [0] :你想要定位的.imageOverlayStyle是被点击的.overlayPicHL的下一个兄弟的.overlayPicHL ,所以使用nextElementSibling[0]

 $(".overlayPicHL").on("click", function() { const imageOverlayStyle = $(this.nextElementSibling).find('.imageOverlayStyle'); $(imageOverlayStyle).css({ backgroundColor: 'yellow' }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer"> <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">overlayPicHL <div class="price"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div> </a> <div class="well photoControlsMain pht-brd-cl"> <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'"> <div class="imageOverlayStyle"> Something here </div> <figure> <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt="" /> <div class="photoControlsMainImage"> <p style="z-index:9999;"> <span class="text-prt-und-bl usernameIndexPos">usernameIndexPos</span> <span class="adRateIndexPos">adrate</span> </p> </div> </figure> </a> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer"> <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">overlayPicHL <div class="price"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div> </a> <div class="well photoControlsMain pht-brd-cl"> <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'"> <div class="imageOverlayStyle"> Something here </div> <figure> <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt="" /> <div class="photoControlsMainImage"> <p style="z-index:9999;"> <span class="text-prt-und-bl usernameIndexPos">usernameIndexPos</span> <span class="adRateIndexPos">adrate</span> </p> </div> </figure> </a> </div> </div>

Add the rules to a stylesheet so that they are automatically applied to the newly created elements.将规则添加到样式表,以便它们自动应用于新创建的元素。 Chain the css() method when you create your elements: $('') .创建元素时链接 css() 方法: $('') 。 appendTo(document. ... Create a new stylesheet dynamically: $(""). appendTo(document. ... 动态创建一个新的样式表:$("")。

$('<img id="newImage" src="text.jpg"/>')
.appendTo(document.body)
.css(style);

Create a new stylesheet dynamically:动态创建一个新的样式表:

$("<style>").text("#myNewEl { width:40px; height:35px; }").appendTo("head");

You can find class in entire document and add css , you can use next() if you want it to add to only next( ) div您可以在整个文档中找到class并添加css ,如果您希望它仅添加到next( ) div,则可以使用next()

 $(document).on("click", ".overlayPicHL", function(){ var id = $(this).attr("data-overlayPicID-id"); $(this).next(".imageOverlayStyle").css({"height":"100%"}); //<-this is the css I want to add to the specific div when the icon has been clicked });
 .imageOverlayStyle { position: absolute; bottom: 0; left: 0; right: 0; background-color: #008CBA; overflow: hidden; width: 100%; height: 0; transition: .5s ease; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'"> <div class="price" style="position:absolute;top:0px;;right:15px;z-index:98;height:50px;width:50px;border-radius: 0px 5px 0px 0px;background-image: linear-gradient(to bottom, rgba(0,0,0,0.8) 50%, rgba(0,0,0,0) 100%);"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div></a> <div class="imageOverlayStyle" id="imgOvrlayID" data-imgOvly-id="'.$row['ad_id'].'"> Something here </div>

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

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