我在使用JavaScript编写脚本时遇到了一个奇怪的事情,我不完全确定我的理解方式是否正确。 基本上我想点击一个按钮,它会弹出另一个按钮,如果第一个按钮没有被第一个按钮调出,我需要退出循环。
var intervalID = window.setInterval(myfunc,1000);
function t(){
console.log('quit');
clearInterval(intervalID);
}
function myfunc(){
//first button
document.getElementsByClassName('hit')[0].click();
//try to retrieve the second one
var el = document.getElementsByClassName('hit_ok');
console.log(el.length);
//if it exists click it
if (el.length == 1){
el[0].click();
//otherwise exit
} else {
console.log('ready to quit');
window.setTimeout(t,50);
}
}
我的问题是第一个实例在if语句中总是返回0 我也尝试了以下内容:
function myfunc(){
document.getElementsByClassName('hit')[0].click();
var el = document.getElementsByClassName('hit_ok');
console.log(el);
if (el != null){
el[0].click();
} else {
console.log('ready to quit');
window.setTimeout(t,50);
}
}
实际上它返回:
[] - > length:0__proto__:HTMLCollection
VM3642:1未捕获的TypeError:无法读取未定义的属性“click”
而不是:
[span.hit_ok]
这意味着第一次无法检索按钮。 显然,第二个按钮就在那里,因为按下了第一个按钮。
HTML code:
//first button
<div class="try">
<input type="hidden" id="isHit" value="">
<a href="javascript:void(0);" class="hit">Try</a>
</div>
//second button
<div class="msgbox_button">
<span class="hit_ok" onclick="remove();">OK</span>
</div>
有什么想法吗?
此致
答案 0 :(得分:0)
你做了什么:
intervalID=window.setInterval();
这是有效的js,但脚本是在页面加载之前启动的,这意味着当时没有创建DOM。
怎么做:
window.onload=function(){
var intervalID=window.Interval(...);
};
这在页面加载后开始循环