NodeList.length始终返回0 [英] NodeList.length is always returning 0

查看:418
本文介绍了NodeList.length始终返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由

var buttons = document.getElementsByName("signupButton");

console.log(buttons);

打印

[item: function]
0: button.btn.btn-warning.btn-lg
1: button.btn.btn-warning.btn-lg
2: button.btn.btn-warning.btn-lg
length: 3
__proto__: NodeList

但是buttons.length正在打印​​0.这里发生了什么?

But buttons.length is printing 0. What is going on here?

推荐答案

这种情况正在发生,因为DOM还没有当你的JS正在执行时加载。它出现在控制台中的原因是因为chrome或者firefox会在DOM更改时更新控制台,实际上会改变控制台中的输出。

This is happening because the DOM has not loaded yet when your JS is executing. The reason its showing up in the console is because chrome, or maybe firefox, will update the console when the DOM changes, essentially changing the output in the console.

为此,你有两个选择:


  • 为DOM加载时注册一个事件处理程序并执行这个$ b那么$ b代码。

  • register an event handler for when the DOM is loaded and execute this code then.

document.addEventListener('DOMContentLoaded',function(){
//代码
//发出AJAX请求单击按钮时
var buttons = document.getElementsByName(signupButton);
});

在结束标记之前移动此脚本标记,以确保DOM在执行时已加载。

move this script tag right before the closing tag to ensure the DOM will have loaded when it gets executed.

< / body>
< script>
//代码
< / script>

这篇关于NodeList.length始终返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆