jQuery - Apply style to center div in a three column row?
I'm trying to add borders to the middle column in a three column row. This:
var subcount = $j('#sub > div').size();
Gives me 6, and I'm trying to figure out how to apply a style to the divs in the middle? (in this case, div 2 and div 5)
<div id="sub">
<div>div 1</div> <div>div 2</div> <div>div3</div>
<div>div 4</div> <div>div 5</div> <div>div6</div>
</div>
Is there a way to do that based on the div # and not the i开发者_高级运维d? Like, some sort of foreach loop or something?
There are lots of ways to do this. It depends on how your data is structured. The brute force way if there are only 6 columns:
$("#sub > div:nth-child(2), #sub > div:nth-child(5)").css("border", "1px solid black");
You can also use an equation with :nth-child
:
$("#sub > div:nth-child(3n+2)").css("border", "1px solid black");
If those are indeed columns, you'd probably be better off using a real table as it's better suited for tabular data. You also haven't marked your rows, which makes selecting the columns difficult. One way to do it would be this:
var n = 1;
$('#sub > div').filter(function() { return n++ % 3 == 2 });
I'll suggest you add some class in code behind, and then apply a clase selector. Or, better, a css style.
If you must use jQuery, cletus solution is just what you want.
Since the Array returned by JQuery is zero-indexed, just run something like this for "div" elements 2 and 5:
$(document).ready(function () {
$("#sub div").filter( function (i) {
return i == 1 || i == 4;
}).css("background", "#b4b0da");
});
精彩评论