NodeList.length始终返回0

编程入门 行业动态 更新时间:2024-10-28 18:36:24
本文介绍了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

本文发布于:2023-10-28 02:32:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NodeList   length

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!