问题
I'm trying to add class to <body>
when <div class="scroll">
has more then 4 <li>text</li>
elements.
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">
. Any body know how to do this by Jquery. Thanks in advance.
回答1:
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(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.
回答2:
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");
}
}
回答3:
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>
来源:https://stackoverflow.com/questions/31635213/add-class-to-body-if-a-div-has-more-then-4-elements