循环按钮总是给我0回答

时间:2017-07-21 14:21:20

标签: javascript javascript-events

这是代码。谢谢你的帮助。

/*this code works fine in code snippet and (when I run the code in the chrome console but when I write the code in my file.js, this won't work*/
var btn = document.getElementsByTagName('button');
alert(btn.length);
// it must alert 3, but I always get 0. Please help me. Thank you
<button>Games</button>
<button>Foods</button>
<button>Movies</button>

1 个答案:

答案 0 :(得分:0)

在文档就绪后运行js。使用window.onload函数

window.onload=function(){
var btn = document.getElementsByTagName('button');
alert(btn.length);
}
<button>Games</button>
<button>Foods</button>
<button>Movies</button>