繁体   English   中英

jQuery each:如果element是第一个子元素,则else

[英]jQuery each: If element is first-child else

因此,我试图在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
     }
});

小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM