【问题标题】:jQuery each: If element is first-child elsejQuery each:如果元素是第一个孩子,否则
【发布时间】:2014-05-17 04:40:07
【问题描述】:

所以我试图在 jQuery 中运行一个 each 循环,它有一个 if 语句来确定它所在的元素是否是它的父元素的第一个子元素,并且后面还有 else 语句(这似乎是困难的部分) 为这些运行其他代码。

我尝试并发现的一切似乎都只在没有 if 和 else 的情况下工作..

有什么想法吗?

【问题讨论】:

  • 你能发布一些你在做什么的代码
  • “有什么想法吗?”关于什么???

标签: javascript jquery if-statement each


【解决方案1】:

举个例子:

<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
    }
});

【讨论】:

    【解决方案2】:

    不会那么难吧?

    $('.elements').each(function(index, elem) {
         if ( $(elem).is(':first-child') ) {
             // it's a baby
         }else{
             // it's something else
         }
    });
    

    FIDDLE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2012-06-12
      • 2018-08-31
      相关资源
      最近更新 更多