【问题标题】:getElementById() in an Array() is overwriting other elements in the arrayArray() 中的 getElementById() 正在覆盖数组中的其他元素
【发布时间】:2013-02-03 22:34:19
【问题描述】:

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

<!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

【问题讨论】:

  • 顺便说一句,在数组上,不要创建命名属性;改为使用索引。

标签: javascript html google-chrome multidimensional-array getelementbyid


【解决方案1】:

做的时候

foo[ bar ] = someValue;

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

你想要实现的,不能用一个简单的数组来实现。

【讨论】:

  • 啊,我明白了。那么有没有办法将每个元素转换成唯一的字符串,使$box['test'][document.getElementById('box')]$box['test'][document.getElementsByTagName('div')[0]] 是相同的值而$box['test'][document.getElementById('boxinfo')] 是不同的。我知道$box['test'][document.getElementById('box').outerHTML] 会起作用,但是还有什么更有效的方法吗?
  • @SuperKingT .outerHTML,即序列化 DOM 以生成唯一字符串将是一个糟糕的解决方案(而且,字符串将 not 保证唯一) .考虑使用自定义函数将 DOM 引用转换为唯一字符串,例如$box.test[ refToStr(document.getElementById('box')) ].
  • @SuperKingT 还可以考虑实现更高级别的 API,例如coll.addElem( box, true )coll.getValue( box ) // returns true.
  • IF 所有浏览器都支持原型继承,您可能会执行类似HTMLElement.prototype.toString = function(){return this.id)} 的操作,但如果假设支持非标准功能、修改主机对象和需要在大量浏览器中已知缺失的功能。但它很有吸引力。并且一些浏览器会主动阻止修改宿主对象。
猜你喜欢
  • 2016-06-30
  • 1970-01-01
  • 2017-07-17
  • 2020-09-27
  • 2013-10-19
  • 2019-10-04
  • 1970-01-01
  • 2018-10-18
  • 2022-11-22
相关资源
最近更新 更多