简体   繁体   English

将类别添加到 <body> 如果一个DIV有4个以上的元素

[英]Add Class to <body> if a DIV has more then 4 elements

I'm trying to add class to <body> when <div class="scroll"> has more then 4 <li>text</li> elements. <div class="scroll">具有超过4个<li>text</li>元素时,我正在尝试向<body>添加类。

HTML: HTML:

 <body>  
   <div class="scroll">
   <div>   <!-- Parent Element -->
     <ul>    <!-- Parent Element 2 -->
     <li>text</li>     <!-- Child 1-->
     <li>text</li>     <!-- Child 2-->
     <li>text</li>     <!-- Child 3-->
     <li>text</li>     <!-- Child 4-->
     <li>text</li>     <!-- Child 5-->
     </ul>
   </div>
   </div>
 <body>

Means if <div class="scroll"> has 5 <li>text</li> item then add class to body like <body class"popup"> . 表示如果<div class="scroll">有5个<li>text</li>项,则将类添加到body例如<body class"popup"> Any body know how to do this by Jquery . 任何人都知道如何通过Jquery做到这一点。 Thanks in advance. 提前致谢。

You can use setInterval (only needed if your li's are added removed dynamically, you may skip it if it's not the case), and check it's length inside and do respective action as needed. 您可以使用setInterval(仅在动态添加了li的情况下才需要,如果不是这种情况,则可以跳过),并检查其长度,并根据需要执行相应的操作。

setInterval(function(){
    if(jQuery('div.scroll ul > li').length > 4)
        jQuery('body').addClass('popup');
    else
        jQuery('body').removeClass('popup');
}, 1000);

Note: You need to place this script before closing of body tag or after of elements for which length needs to be compared. 注意:您需要将此脚本放置在body标签关闭之前或需要比较其长度的元素之后。

I think you're after something like the following. 我认为您正在追随以下情况。

$(function() {
    //Will execute as soon as the DOM is loaded
    addBodyClass();

    //Let's say a click function somewhere deletes a LI
    $("selector").on("click", function() {
        $('.scroll li:last').remove();
        //Now there are 4 LIs which means remove the popup class from body
        //So, call the function again
        addBodyClass();
    });

});

function addBodyClass() {

    $('.scroll li').length > 4 && $("body").addClass("popup") || $("body").removeClass("popup");

    //The above is the shorter version of
    if ($('.scroll li').length > 4) {
        $("body").addClass("popup");
    } else {
        $("body").removeClass("popup");
    }
}

This should Work for you 这应该为你工作

<script type="text/javascript">

   $(document).ready(function(){

   if ($('.scroll li').length > 4) {
     $("body").addClass("popup");
    } else {
     $("body").removeClass("popup");
   }

 });


</script>

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

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