所以我正在尝试在jQuery中运行一个每个循环,该循环有一个if语句来确定它所在的元素是否是其父元素的第一个子元素,并且还有else语句跟随(这似乎是困难的部分)让其他代码为这些代码运行。
我尝试和发现的一切似乎只有在没有if和else的情况下才能工作。
有什么想法吗?
给出以下示例:
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
有几种方法可以做到这一点
$("table tr td:first-child").each(function() {
//perform actions on all of the first TD elements
});
$("table tr td:not(:first-child)").each(function() {
//perform actions on all of the other TD elements
});
或
$("table tr td").each(function() {
var td = $(this);
if (td.is(":first-child")) {
//perform actions on all of the first TD elements
}
else {
//perform actions on all of the other TD elements
}
});
不会那么难吗?
$('.elements').each(function(index, elem) {
if ( $(elem).is(':first-child') ) {
// it's a baby
}else{
// it's something else
}
});
小提琴