[英]Selecting alternate boxes in n number of elements using jquery/javascript
I am working on a project and getting data in form of json
objects. 我正在做一个项目,并以
json
对象的形式获取数据。 I am displaying data in perfectly in the boxes as depicted below (current). 我正在如下图所示的框中完美地显示数据(当前)。 But I want to add class on alternative boxes for different colors as depicted below (required).
但是我想在不同颜色的替代盒子上添加类,如下所示(必需)。
Code: 码:
jQuery.each(Stories, function (index) {
var lindex = 6 * PageID;
var findex = lindex - 6;
if (index + 1 > findex && index + 1 <= lindex) {
var stories = dvStoreies;
if ((index) % 3 == 0) {
stories.append("<div class='dvStoriesFirst' style='clear:left;float:left;margin-bottom:40px;' ID=story_" + index + "></div>");
}
else {
stories.append("<div class='dvStories' style='float:left;margin-bottom:40px;' ID=story_" + index + "></div>");
}
}
});
HTML Looks Like This: HTML看起来像这样:
<div class="stories">
<div class="dvStoriesFirst" id="s_box1"></div>
<div class="dvStories" id="s_box2"></div>
<div class="dvStories" id="s_box3"></div>
<div class="dvStoriesFirst" id="s_box4"></div>
<div class="dvStories" id="s_box5"></div>
<div class="dvStories" id="s_box6"></div>
</div>
Can anyone one help me how can I achieve this. 任何人都可以帮助我如何实现这一目标。 Thanks
谢谢
If your boxes are added in this order left to right one row after another
, it should be as simple as testing if the box number modulo 3 modulo 2 is 0, ie: 如果您的框是按此顺序
left to right one row after another
依次添加的,那么它就像测试框号3取模2是否为0一样简单,即:
var shouldHighlight = (zeroBasedBoxNumber % 3 % 2) === 0;
So with your code (and with some missing ID and css class): 因此,使用您的代码(以及缺少的ID和CSS类):
jQuery.each(Stories, function(index, story) {
var style = ['float: left', 'margin-bottom: 40px'];
if (index % 3 === 0) style.push('clear: left');
if (index % 3 % 2 === 0) style.push('background-color: #aaa');
dvStoreies.append('<div style="' + style.join(';') + '"></div>');
});
If You want to apply the class Alternatively, it should be 如果您想申请该课程,则应该
if ((index) % 3 % 2 == 0)
hope so it helps 希望有帮助
Here is an working example 这是一个有效的例子
<div class="stories">
<div class="dvStories" id="s_box1"></div>
<div class="dvStories" id="s_box2"></div>
<div class="dvStories" id="s_box3"></div>
<div class="dvStories" id="s_box4"></div>
<div class="dvStories" id="s_box5"></div>
<div class="dvStories" id="s_box6"></div>
<div class="dvStories" id="s_box7"></div>
<div class="dvStories" id="s_box8"></div>
<div class="dvStories" id="s_box9"></div></div>
JS Code JS代码
$('.dvStories').each(
function(index,div){
if(index % 3==0){
$(div).css({clear:"left"});
}
if ((index) % 3 % 2 == 0){
$(div).addClass('orangeBG');
}
});
CSS CSS
.dvStories{
width:100px;height:100px;
background:grey;
margin:2px;
float:left;
}
.orangeBG{
background:orange;
}
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.