jquery - 使用 jQuery “each” 来设置树的样式

标签 jquery css arrays foreach each

我正在使用这段代码来设置元素树的样式:

 $('.js-toprow').each(function(index) {
        if (index % 2 === 0) { // Even
          $(this).css('background', '#ddd');
        } else { // Odd
          $(this).css('background', '#ff0000');
        }        
    });

我在这里试图实现的是,我需要一个元素为偶数,一个元素为奇数。 它工作得很好,除了在元素 4 或 5 周围,最后两个元素的颜色相同。看看屏幕截图。

在这里 fiddle :https://jsfiddle.net/865ytmkd/35/

看起来幻灯片放映代码移动了可能是问题所在的元素。

完整代码:

jQuery(function ($) {

$("#jobshome").load("jobs/newest-jobs .js-toprow", function(){
    //rotation speed and timer
    var speed = 4000;
    var run = setInterval(rotate, speed);
    var slides = $('.js-toprow');
    var container = $('#jobshome');
    var elm = container.children(':first-child').prop("tagName");
    var item_height = container.height();
    var previous = 'prevabc'; //id of previous button
    var next = 'nextabc'; //id of next button
    slides.height(item_height); //set the slides to the correct pixel height
    container.parent().height(item_height);
    container.height(slides.length * item_height); //set the slides container to the correct total height
    container.children(elm + ':first').before(container.children(elm + ':last'));
    resetSlides(); 


    //if user clicked on prev button

    $('#buttonsabc a').click(function (e) {
        //slide the item

        if (container.is(':animated')) {
            return false;
        }
        if (e.target.id == previous) {
            container.stop().animate({
                'top': 0
            }, 1000, function () {
                container.children(elm + ':first').before(container.children(elm + ':last'));
                resetSlides();
            });
        }

        if (e.target.id == next) {
            container.stop().animate({
                'top': item_height * -2
            }, 1000, function () {
                container.children(elm + ':last').after(container.children(elm + ':first'));
                resetSlides();
            }
      );
    }
        //cancel the link behavior            
        return false;

    });

    //if mouse hover, pause the auto rotation, otherwise rotate it    
    container.parent().mouseenter(function () {
        clearInterval(run);
    }).mouseleave(function () {
        run = setInterval(rotate, speed);
    });


    function resetSlides() {
        //and adjust the container so current is in the frame
        container.css({
            'top': -1 * item_height
        });
    }


$('.js-toprow').each(function(index) {
    if (index % 2 === 0) { // Even
      $(this).css('background', '#f4f5f7');
    } else { // Odd
      $(this).css('background', '#ffffff');
    }  

});


});
//a simple function to click next link
//a timer will call this function, and the rotation will begin

function rotate() {
    jQuery('#nextabc').click();
}

});

1 Elements with different colors,you may need to adjust your screen brightness

2 Elements with the same color, The problem

3 The tree showing the elements with the same color

另一个截图:/image/GnhHM.jpg

最佳答案

CSS 将是更好、更简单的解决方案,但如果您想坚持使用此代码,那么问题出在 if 条件下。 将 if 条件中的索引替换为 (index + 1)

$('.js-toprow').each(function(index) {
        if ((index+1) % 2 === 0) { // Even
          $(this).css('background', '#ddd');
        } else { // Odd
          $(this).css('background', '#ff0000');
        }        
    });

这是一个 CSS 解决方案。

#jobshome > div:nth-child(even) {background: #f4f5f7}
#jobshome > div:nth-child(odd) {background: #CCC}

更新 1:

我正在更新答案以删除将幻灯片 div 从第一个元素旋转到最后一个元素的代码。查找注释行(删除此行)。

jQuery(function ($) {

$("#jobshome").load(".js-toprow", function(){
    //rotation speed and timer
    var speed = 4000;
    var run = setInterval(rotate, speed);
    var slides = $('.js-toprow');
    var container = $('#jobshome');
    var elm = container.children(':first-child').prop("tagName");
    var item_height = container.height();
    var previous = 'prevabc'; //id of previous button
    var next = 'nextabc'; //id of next button
    slides.height(item_height); //set the slides to the correct pixel height
    container.parent().height(item_height);
    container.height(slides.length * item_height); //set the slides container to the correct total height
    container.children(elm + ':first').before(container.children(elm + ':last'));
    resetSlides(); 
    
    
    //if user clicked on prev button
    
    $('#buttonsabc a').click(function (e) {
        //slide the item
        
        if (container.is(':animated')) {
            return false;
        }
        if (e.target.id == previous) {
            container.stop().animate({
                'top': 0
            }, 1000, function () {
               // container.children(elm + ':first').before(container.children(elm + ':last'));REMOVING THIS LINE.
                resetSlides();
            });
        }
        
        if (e.target.id == next) {
            container.stop().animate({
                'top': item_height * -2
            }, 1000, function () {
                //container.children(elm + ':last').after(container.children(elm + ':first')); REMOVING THIS LINE.
                resetSlides();
            }
      );
    }
        //cancel the link behavior            
        return false;
        
    });
    
    //if mouse hover, pause the auto rotation, otherwise rotate it    
    container.parent().mouseenter(function () {
        clearInterval(run);
    }).mouseleave(function () {
        run = setInterval(rotate, speed);
    });
    
    
    function resetSlides() {
        //and adjust the container so current is in the frame
        container.css({
            'top': -1 * item_height
        });
    }

    
$('.js-toprow').each(function(index) {
        if ((index+1) % 2 === 0) { // Even
          $(this).css('background', '#ddd');
        } else { // Odd
          $(this).css('background', '#ff0000');
        }        
    });

	
});
//a simple function to click next link
//a timer will call this function, and the rotation will begin

function rotate() {
    jQuery('#nextabc').click();
}

});
#carouselabc {
position: relative;
width:100%;
margin:0 auto;
}

#slidesabc {
overflow: hidden;
position: relative;
width: 100%;
height:220px;
}

#areadoslideabc {
list-style: none;
width:100%;
height:220px;
margin: 0;
padding: 0;
position: relative;
}

 #slidesabcdef {
width:100%;
height:220px;
float:left;
text-align: center;
position: relative;
font-family:lato, sans-serif;
}
/* Styling for prev and next buttons */
.btn-barabc{
    /* margin: 0 auto 0 auto; */
    /* display: table; */
    position: relative;
    width: 100%;
}
 #buttonsabc {
 display: flex;  align-items: center;
  justify-content: center;     position: relative;
 }

#buttonsabc a {
text-align: center;
    font-size: 20px;
	font-weight:bolder;
    outline: 0;
    margin: 5px 10px 5px 10px;
    padding: 0px 5px;
    text-decoration: none;
    display: table;
    color: #cb2027;
    border-radius: 100%;
    -moz-border-radius: 100%;
    -webkit-border-radius: 100%;
    border: solid 0.2rem #385778;
    background: #ffffff;
}
a#prevabc, a#nextabc { display:table }
a#prevabc:hover, a#nextabc:hover {
color:#000;
text-shadow:.5px 0px #b14943;  
}




#wrapper {height:220px;  margin:0; padding:0 }




@media screen and (max-width: 849px) {
.latestjobs #jobshome {
text-align:center }
.latestjobs .js-image { display: table; float: none; width:40%; margin:auto; padding: 0px 0px 5px 0px;}
.latestjobs .js-data { display: table; width: 100%;}
}
@media screen and (min-width: 850px) {
.latestjobs #jobshome { 
text-align:left}
.latestjobs .js-image { display: table; float: left; width: 30%;     padding: 10px 10px 0 5px;}
.latestjobs .js-data { display: table; width: 69%;}
}
	
.latestjobs { border: 1px solid #E3E3E3 ; text-align: center !important; clear:both !important; 	background-color: #efefef;

}
.latestjobs #jobshome {
width:100%; height:220px;
padding: 0;
margin:0;  position:relative}
.latestjobs .js-toprow { overflow: inherit; height:inherit;   padding: 10px 0 10px 0;}
/*.latestjobs .js-toprow:nth-child(even) { background: #efefef; }
.latestjobs .js-toprow:nth-child(odd) { background:#fbfbfb; }*/


.latestjobs  .js-bold, .js-type, .js-bold { font-weight:bolder; color: #000;}

.latestjobs a.jobtitle { padding-right: 15px; }
.latestjobs span.js-type {  display: table; float: right;   padding: 4px;  margin-left: 10px; margin-right: 10px; border: solid thin;  display: table;  padding-left: 10px; }
.latestjobs span.js-type{ background:transparent}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">



<div class="moduletable latestjobs">
							<h3 class="g-title">Latest jobs</h3>
						

<div class="customlatestjobs">
	<link rel="stylesheet" type="text/css" href="/go/scripts/jqueryautoscroll/autoscroll.css">

<!-- Auto Scroll -->
<script src="/go/scripts/jqueryautoscroll/autoscroll.js"></script>


<div id="carouselabc">
    <div id="slidesabc" style="height: 220px;">
<div id="jobshome" style="height: 1100px; top: -220px;"><div class="js-toprow" style="height: 240px; background: rgb(255, 255, 255);"><div class="js-image"><a href="/jobs/company-detail/company-1/nav-31"><img src="https://fleamerica.com/jsjobsdata/data/employer/comp_1/logo/logo-for-hotlinking_important[1].png" title="FleAmerica Jobs"></a></div><div class="js-data"><div class="js-first-row"><span class="js-col-xs-12 js-col-md-6 js-title js-title-tablet"> <a class="jobtitle" href="/jobs/job-detail/job-accountant-3">Accountant</a></span><span class="js-col-xs-12 js-col-md-6 js-jobtype js-jobtype-tablet">Posted: 782 Days Ago<span class="js-type">Full-Time</span></span></div><div class="js-second-row"><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Category: </span>Computer/IT</div><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Salary Range: </span>$ 4000 - 4500 Per Month</div><div class="js-col-xs-12 js-col-md-2 js-fields no-padding"> <span class="js-totaljobs">1 Jobs</span></div></div>
                            </div>
                        </div><div class="js-toprow" style="height: 240px; background: rgb(244, 245, 247);"><div class="js-image"><a href="/jobs/company-detail/company-1/nav-31"><img src="https://fleamerica.com/jsjobsdata/data/employer/comp_1/logo/logo-for-hotlinking_important[1].png" title="FleAmerica Jobs"></a></div><div class="js-data"><div class="js-first-row"><span class="js-col-xs-12 js-col-md-6 js-title js-title-tablet"> <a class="jobtitle" href="/jobs/job-detail/job-senior-software-engineer-4">Senior Software Engineer</a></span><span class="js-col-xs-12 js-col-md-6 js-jobtype js-jobtype-tablet">Posted: 782 Days Ago<span class="js-type">Full-Time</span></span></div><div class="js-second-row"><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Category: </span>Computer/IT</div><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Salary Range: </span>$ 4500 - 5000 Per Month</div><div class="js-col-xs-12 js-col-md-2 js-fields no-padding"> <span class="js-totaljobs">1 Jobs</span></div></div>
                            </div>
                        </div><div class="js-toprow" style="height: 240px; background: rgb(244, 245, 247);"><div class="js-image"><a href="/jobs/company-detail/company-1/nav-31"><img src="https://fleamerica.com/jsjobsdata/data/employer/comp_1/logo/logo-for-hotlinking_important[1].png" title="FleAmerica Jobs"></a></div><div class="js-data"><div class="js-first-row"><span class="js-col-xs-12 js-col-md-6 js-title js-title-tablet"> <a class="jobtitle" href="/jobs/job-detail/job-web-designer-5">Web Designer</a></span><span class="js-col-xs-12 js-col-md-6 js-jobtype js-jobtype-tablet">Posted: 782 Days Ago<span class="js-type">Full-Time</span></span></div><div class="js-second-row"><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Category: </span>Computer/IT</div><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Salary Range: </span>$ 1000 - 1500 Per Month</div><div class="js-col-xs-12 js-col-md-2 js-fields no-padding"> <span class="js-totaljobs">1 Jobs</span></div></div>
                            </div>
                        </div><div class="js-toprow" style="height: 240px; background: rgb(255, 255, 255);"><div class="js-image"><a href="/jobs/company-detail/company-1/nav-31"><img src="https://fleamerica.com/jsjobsdata/data/employer/comp_1/logo/logo-for-hotlinking_important[1].png" title="FleAmerica Jobs"></a></div><div class="js-data"><div class="js-first-row"><span class="js-col-xs-12 js-col-md-6 js-title js-title-tablet"> <a class="jobtitle" href="/jobs/job-detail/job-php-developer-1">PHP Developer</a></span><span class="js-col-xs-12 js-col-md-6 js-jobtype js-jobtype-tablet">Posted: 782 Days Ago<span class="js-type">Full-Time</span></span></div><div class="js-second-row"><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Category: </span>Computer/IT</div><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Salary Range: </span>$ 1000 - 1500 Per Month</div><div class="js-col-xs-12 js-col-md-2 js-fields no-padding"> <span class="js-totaljobs">2 Jobs</span></div></div>
                            </div>
                        </div><div class="js-toprow" style="height: 240px; background: rgb(244, 245, 247);"><div class="js-image"><a href="/jobs/company-detail/company-1/nav-31"><img src="https://fleamerica.com/jsjobsdata/data/employer/comp_1/logo/logo-for-hotlinking_important[1].png" title="FleAmerica Jobs"></a></div><div class="js-data"><div class="js-first-row"><span class="js-col-xs-12 js-col-md-6 js-title js-title-tablet"> <a class="jobtitle" href="/jobs/job-detail/job-games-developer-2">Android Developer</a></span><span class="js-col-xs-12 js-col-md-6 js-jobtype js-jobtype-tablet">Posted: 782 Days Ago<span class="js-type">Full-Time</span></span></div><div class="js-second-row"><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Category: </span>Computer/IT</div><div class="js-col-xs-12 js-col-md-5 js-fields"><span class="js-bold">Job Salary Range: </span>$ 2500 - 3000 Per Month</div><div class="js-col-xs-12 js-col-md-2 js-fields no-padding"> <span class="js-totaljobs">3 Jobs</span></div></div>
                            </div>
                        </div></div>
</div>
  <div class="btn-barabc">
    <div id="buttonsabc">    <a id="prevabc" href="#">&lt; &lt;</a><a id="nextabc" href="#">&gt; &gt;</a> 
  </div></div>
</div>



<!--   Source:https://codepen.io/TyStelmach/pen/yygvNK
<script>//jQuery("#jobshome").load("jobs/newest-jobs .js-toprow"); </script>
 --></div>
		</div>		</div>

关于jquery - 使用 jQuery “each” 来设置树的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52316026/

相关文章:

javascript - 使用 jQuery 删除 iframe 中的 body 标签

html - css中的宽度百分比%和像素有什么区别

javascript - 通过组合相同元素来变换数组

javascript - 类与 jquery 比较

javascript - jquery:如何选择属性名称中包含数组值的复选框?

javascript - 仅针对选定元素的 css 样式

css - 在我的容器中居中登录网格?

java - 遍历数组并检查项目的值

javascript - 在javascript中通过路径将值插入数组

javascript - 使用 XML 作为源重新加载 DIV 的内容