简体   繁体   English

Javascript:在页面加载时按类名获取所有元素不起作用

[英]Javascript: get all elements by class name on page load NOT WORKING

I'm trying to create a script that would transform existing elements on page to new ones when the page loads, but fail, obviously. 我正在尝试创建一个脚本,该脚本将在页面加载时将页面上的现有元素转换为新元素,但是显然会失败。

Here's a really weird output of an array of those elements (states three elements are there, but shows only one): 这是这些元素数组的一个非常奇怪的输出(声明那里有三个元素,但只显示一个):

在此处输入图片说明

 <html> <head> <script> var f__inputs = []; document.addEventListener('DOMContentLoaded', function () { f__init(); }, false); function f__init(){ f__inputs = document.body.getElementsByClassName("superinput"); console.log(f__inputs); f__insert(); } function f__insert(){ for(var i=0;i<f__inputs.length;i++){ f__inputs[i].id = "superinput-wrapper-" + i; f__inputs[i].className = "superinput-wrapper"; var d = f__inputs[i].getAttribute("data-fields"); for(var j=0;j<d;j++){ var input = document.createElement("input"); input.setAttribute("data-wrap",i); input.setAttribute("data-pos",j); input.setAttribute("size","1"); input.setAttribute("type","text"); input.id = "superinput-input-" + j; input.className = "superinput-input"; if(j!=0){ input.setAttribute("disabled","true"); input.disabled = true; } f__inputs[i].appendChild(input); } } } </script> </head> <body> <p> <b>Task 90.</b> Lorem ipsum dolor sit amet... <div class="superinput" data-fields="6"></div> </p> <p> <b>Task 91.</b> Lorem ipsum dolor sit amet... <div class="superinput" data-fields="6"></div> </p> <p> <b>Task 91.</b> Lorem ipsum dolor sit amet... <div class="superinput" data-fields="6"></div> </p> </body> </html> 

Any idea why is that happening? 知道为什么会这样吗?

Two things. 两件事情。

  1. Mouse over the [i] and you'll see it tells you that the values of the array are "frozen" when you expand it and may not reflect the realtime values. 将鼠标悬停在[i]上,您会看到它告诉您,展开数组时数组的值是“冻结的”,并且可能无法反映实时值。

  2. getElementsByClassName is a live list . getElementsByClassName活动列表 This means when you set className = "something-else" , it is removed from the list. 这意味着当您设置className = "something-else" ,该名称将从列表中删除。 For this reason, it is recommended that you loop through them using for( i=l-1; i>=0; i--) instead of the usual loop. 因此,建议您使用for( i=l-1; i>=0; i--)而不是通常的循环来遍历它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM