我有一个由
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
发布评论