代码之家  ›  专栏  ›  技术社区  ›  SoLoGHoST

下一个问题应该很简单

  •  1
  • SoLoGHoST  · 技术社区  · 16 年前

    好的,我正在尝试处理JS中的下一个函数。以下是我的问题代码…

    var fromRow = document.getElementById("row_1");
    
    while(fromRow.nodeType == 1 && fromRow.nextSibling != null)
    {
        var fRowId = fromRow.id;
        if (!fRowId) continue;
    
        // THIS ONLY gets done once and alerts "row_1" ONLY :(
        alert(fRowId);
    
        fromRow = fromRow.nextSibling;
    }
    

    好的,有人能告诉我这个代码有什么问题吗?旁边有兄弟姐妹 document.getElementById("row_1"); 元素,正如我所看到的,它们都有ID属性,那么为什么它不能获取兄弟姐妹的ID属性呢?我不明白。

    row_1 是一个 TR 元素,我需要得到 TR 在这个表中,它旁边的元素,但是由于某种原因,它只得到我已经可以使用的1个元素 document.getElementById ,阿格格。

    谢谢大家:

    2 回复  |  直到 16 年前
        1
  •  2
  •   Andy E    16 年前

    尝试:

    var fromRow = document.getElementById("row_1");
    
    while(fromRow !== null)
    {
        var fRowId = fromRow.id;
        if (!fRowId || fromRow.nodeType != 1) {
            fromRow = fromRow.nextSibling;
            continue;
        }
    
        // THIS ONLY gets done once and alerts "row_1" ONLY :(
        alert(fRowId);
        fromRow = fromRow.nextSibling;
    }
    

    同时 fromRow.nextSibling != null 将在第二次到最后一次迭代时停止,因为您已经设置了 fromRow 对其 nextSibling 最后。另外,如果下一个节点不是元素,则不一定要停止,如果可能,只希望移动到下一个节点。最后,如果你点击 continue 在您最初的示例中,您将遇到一个无止境的循环,因为 从一排开始 永远不会改变价值。

        2
  •  2
  •   Paul Wagener    16 年前

    当遇到非类型1的节点时,while循环将立即停止。因此,如果元素之间有任何空白,while循环将在第一个元素之后中断。

    你可能想要的是:

    while(fromRow.nextSibling != null)
    {
        if(fromRow.nodeType == 1) {
            ...
        }
    }