getelementbytagname上的Javascript问题
Javascript issue on getelementbytagname
我在使用以下代码时遇到了一些问题:
var lista_input = document.getElementsByTagName("input");
console.log(lista_input);
console.log(lista_input[0]);
第一个日志正确地显示了我:
[item: function]
0: input
1: input
length: 2
__proto__: NodeList
但第二条日志显示:
undefined
我不明白原因,它可能会向我显示dom中的第一个元素输入!
问题是由于document.getElementsByTagName
的返回值是一个活动NodeList:
var l = document.getElementsByTagName('div');
console.log(l[0]); // undefined
var d = document.createElement('div');
document.body.appendChild(d);
console.log(l[0]); // div
再加上您在文档准备好之前(因此在列表中有项目之前)调用代码的事实,以及Console代码中的已知错误,该错误可以在调用console.log
之后显示处于状态的对象,您就有了正在经历的确切行为。
重申:
var lista_input = document.getElementsByTagName("input");
// lista_input is a live NodeList with 0 elements
console.log(lista_input); // will print the lista_input object at a later point
console.log(lista_input[0]); // will print undefined at a later point
/* time passes, dom is loaded */
// lista_input now has the inputs you expect it to have
/* time passes */
// logs are now shown in Console
编辑:为了获得一个好的日志,你可以在记录对象时将其字符串化,将其转换为一个正确记录的基元值:
var lista_input = document.getElementsByTagName("input");
console.log(JSON.stringify(lista_input)); // {"length":0} - empty list
console.log(JSON.stringify(lista_input[0])); // undefined
PS:链接到解释Console错误的博客文章:http://techblog.appnexus.com/2011/webkit-chrome-safari-console-log-bug/
链接到请求修复控制台错误的问题:如何更改console.log的默认行为?(*safari中的错误控制台,没有附加组件*)
相关文章:
- 我不知道我的编码有什么问题.(JavaScript)
- 登录后重定向,缓存页面问题-Javascript
- 在我的网站上创建一个在1-10之间不断变化的数字时遇到了问题.Javascript
- 浮点数字问题JavaScript
- 局部全局变量问题 - JavaScript
- 内容滑块问题 javascript
- 多个脚本导致链接问题?Javascript、CSS、HTML、Jquery
- 基本范围问题(javascript和node)
- 表单验证问题(Javascript)
- 表杂乱无章的问题.Javascript HTML5.
- 我的代码有什么问题.JavaScript幻灯片
- 这段代码有什么问题?(JavaScript)
- 浏览器和移动设备的视差背景问题(javascript/jquery)
- Mozilla中的setInterval()问题(Javascript函数)
- While循环问题-JavaScript-jQuery.Clone()
- 检查密码匹配问题(JavaScript)
- 抓取选中单选按钮的问题- JavaScript
- 基于下拉选择禁用文本字段的问题(JavaScript)
- 比较日期问题- javascript
- 浏览器兼容性问题Javascript