【问题标题】:JavaScript array changes when DOM changes [duplicate]DOM更改时JavaScript数组更改[重复]
【发布时间】:2015-10-24 17:23:33
【问题描述】:

我将 document.getElementsByClassName("red") 的结果分配给数组 redElements。然后,我将一个元素从 .red 类更改为 .blue 类。我希望 redElements 保持原来的三个值,但它现在只包含两个仍然是红色的元素。这是令人惊讶的。这是什么原因?我应该查看什么来详细了解为什么会发生这种情况?

<!DOCTYPE html>
<html>
    <head>
        <style>
            .red { color: red; }
            .blue { color: blue; }
        </style>
    </head>
    <body>

        <span class="red">1</span>
        <span class="red">2</span>
        <span class="red">3</span>

        <script>
            var redElements = document.getElementsByClassName("red");
            alert(redElements.length);
            firstRedElement = redElements[0];
            firstRedElement.className = "blue";
            alert(redElements.length);
        </script>
    </body>
</html>

【问题讨论】:

  • redElements 不是document.getElementsByClassName("red")副本 - 它是相同的元素集合!
  • 这个问题与建议的“重复”无关。请多加注意!
  • 我同意关闭。正如其他问题中所解释的那样,这是因为该集合是实时的。
  • @Oriol 不,这是因为 redElements 是对同一集合的引用。它不一定是一个集合,它可以是一个对象引用,数组引用,与“live”无关。
  • @James 如果您使用document.querySelectorAll(".red"),您还将获得对该集合的引用。但它不是实时的,所以它没有这个问题。

标签: javascript dom getelementsbyclassname


【解决方案1】:

那是因为className 函数会覆盖现有的类:
试试这个:

<script>
        var redElements = document.getElementsByClassName("red");
        alert(redElements.length);
        firstRedElement = redElements[0];
        firstRedElement.className = firstRedElement.className + " blue";
        alert(redElements.length);
    </script>

或者你甚至可以尝试:

firstRedElement.classList.add("blue");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2017-09-02
    • 2017-07-31
    • 2020-11-29
    • 2012-02-02
    • 2016-02-08
    • 1970-01-01
    • 2013-12-21
    相关资源
    最近更新 更多