Array() 中的 getElementById() 正在覆盖数组中的其他元素

getElementById() in an Array() is overwriting other elements in the array

本文关键字:元素 数组 其他 中的 getElementById Array 覆盖      更新时间:2023-09-26

我觉得这应该有一个非常简单的答案,但我仍然挠头,谷歌没有帮助。我正在尝试在数组中存储有关元素的信息。但是在谷歌浏览器中,当我设置有关第二个元素的信息时,它会覆盖第一个元素。以下是代码的简化版本:

<!DOCTYPE HTML>
<html>
  <head>
    <script>
      var $box = new Array();
      $box['test'] = new Array();
      function load(){
        $box['test'][document.getElementById('box')] = true;
        $box['test'][document.getElementById('boxinfo')] = false;
        console.log('box: ' + $box['test'][document.getElementById('box')]);                // box: false      // Should be true
        console.log('boxinfo: ' + $box['test'][document.getElementById('boxinfo')]);        // boxinfo: false  // Should be false
        console.log(document.getElementById('box') == document.getElementById('boxinfo'));  // false           // Should be false
      }
    </script>
  </head>
  <body onload="load();">
    <div id="box">
      <div id="boxinfo">BoxInfo</div>
      Box
    </div>
  </body>
</html>

我怎样才能做到

$box['test'][document.getElementById('box')]          // is true
$box['test'][document.getElementsByTagName('div')[0]] // is true
$box['test'][document.getElementById('boxinfo')]      // is false

做的时候

foo[ bar ] = someValue;

bar将转换为 String 值,然后将其用作属性名称(正在分配给该名称)。在您的情况下,您的 DOM 元素将转换为字符串,例如 '[object HTMLDivElement]' .如果两个元素都是 DIV,它们将被转换为相同的 String 值,这就是第二个赋值覆盖第一个赋值的原因,即两个赋值都分配给同一个属性。

您要实现的目标不能用简单的数组来实现。