Button元素在第一次调用时未被检索

Button element is not retrieved at the first call

本文关键字:检索 调用 元素 第一次 Button      更新时间:2023-09-26

我在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 Uncaught TypeError: Cannot read property 'click' of undefined

代替:[span.hit_ok]

这意味着第一次它不能检索按钮。显然,第二个按钮在那里,因为第一个按钮被按下了。

HTML代码:

//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>

任何想法?

认为,

你做了什么:

intervalID=window.setInterval();

这是有效的js,但脚本是在页面加载之前启动的,这意味着DOM当时没有创建。

怎么做:

window.onload=function(){
var intervalID=window.Interval(...);
};

在页面加载完毕后开始循环