问题
I have a NodeList object that is created by
var buttons = document.getElementsByName("signupButton");
console.log(buttons);
prints
[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
But buttons.length is printing 0. What is going on here?
回答1:
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.
In order for this to work, you have two options:
register an event handler for when the DOM is loaded and execute this code then.
document.addEventListener('DOMContentLoaded', function(){ // the code //make AJAX request when button is clicked var buttons = document.getElementsByName("signupButton"); });
move this script tag right before the closing tag to ensure the DOM will have loaded when it gets executed.
</body> <script> // the code </script>
来源:https://stackoverflow.com/questions/26894000/nodelist-length-is-always-returning-0