【问题标题】:Unexpected element when calling getElementByTagName [duplicate]调用 getElementByTagName 时出现意外元素 [重复]
【发布时间】:2022-11-22 05:29:39
【问题描述】:

我是 javascript 的新手,不明白为什么当我调用 getElementByTagName() 时在集合中循环时我的标签后得到一个函数作为输出;

我对英语一窍不通,所以这里有一个 sn-p 可以帮助您弄清楚我的问题是什么。

function div1ParaElems() {
            const div1 = document.getElementById("div1");
            const div1Paras = div1.getElementsByTagName("div");
            const num = div1Paras.length;
            alert(`There are ${num} paragraph in #div1`);
            let out = document.getElementById("output");
            for (let i in div1Paras){
                out.innerHTML += div1Paras[i] + "<br>";
        div1Paras[i].addEventListener("click",alertMe);
            }
        }
        function alertMe(e){
            alert(e.target.innerHTML);
        }
*{
            box-sizing: border-box;
        }
        .flexTest{
            display: flex;
            flex: auto;
            flex-wrap: wrap;
            align-items: flex-start;
            /*justify-content: space-around;*/
            /*justify-content: space-between;*/
            border:1px solid #D2D2D2;
            background-color: burlywood;
        }
        .flexTest div{
            background-color: antiquewhite;
            padding:10px;
            margin:10px;
            display: flex;
            flex: content;
            border:1px solid #D2D2D2;
        }
<body onLoad="div1ParaElems()">
    <div id="div1" class="flexTest">
        <div>
            Tatactic - Nicolas 1
        </div>
        <div>
            Tatactic - Nicolas 2
        </div>
        <div>
            Tatactic - Nicolas 3
        </div>
        <div>
            Tatactic - Nicolas 4
        </div>
        <div>
            Tatactic - Nicolas 5
        </div>
        <div>
            Tatactic - Nicolas 6
        </div>
        <div>
            Tatactic - Nicolas 7
        </div>
        <div>
            Tatactic - Nicolas 8
        </div>
    </div>
    <div id="output"></div>
</body>

为什么即使它不是 div 元素,我的输出末尾也会出现 function item() { [native code] }???

预先感谢您的时间和耐心!

输出包含 9 个元素,而不是预期的 8 个。

[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
[object HTMLDivElement]
function item() { [native code] }

【问题讨论】:

  • 运行你的 sn-p,我只看到 [object HTMLDivElement] 3 次,然后它抛出“错误:”Uncaught TypeError: div1Paras[i].addEventListener is not a function”
  • 可以投反对票,但我只想了解这一点。如果您有答案,请随时添加答案。谢谢你。

标签: javascript html tags


【解决方案1】:

这是因为您正在使用 for..in,它将 div1Paras 视为对象,迭代其属性(包括 lengthitem 方法等)。您可能想改用 for..of

for (let div of div1Paras) {
  out.innerHTML += div + "<br>";
  div.addEventListener("click", alertMe);
}

【讨论】:

  • 我会试试的。谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 2020-07-20
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多