如何创建一个事件侦听器来检测布尔变量是否为真?

2022-01-15 00:00:00 events event-handling jquery javascript

例如,我有 var menu_ready = false;.我有一个 ajax 函数,它在 ajax 完成后将 menu_ready 设置为 true:

//这里设置事件监听$(...).load(..., function() {...菜单就绪=真;}

如何设置等待 menu_ready 为真的事件侦听器?

解决方案

警告 我下面的回答来自五月花号航行之前的一段时间.这是一个糟糕的答案.我无法删除它,因为它已被接受,并且系统不会让我删除已接受的答案.我可以对其进行编辑以使其变得更好,但是当其他人在下面给出可靠的答案时,为什么要这样做呢?底线:滚动过去,过上更充实的生活.:)

<BAD-ANSWER>

<块引用>

一种方法是持续轮询:

function checkMenu() {如果(!menu_ready){setTimeout(checkMenu();", 1000);返回;} 别的 {//menu_ready 是真的,所以在这里做你需要做的.}}

还有……

<body onload="checkMenu();">

</BAD-ANSWER>

For example, I have var menu_ready = false;. I have an ajax function that sets menu_ready to true when the ajax stuff is done:

//set up event listener here

$(...).load(..., function() {
    ...
    menu_ready = true;
}

How do I set up an event listener that waits for menu_ready to be true?

解决方案

WARNING My answer below is from a period slightly prior to the sailing of the Mayflower. It's a bad answer. I can't remove it because it was accepted, and the system won't let me remove an accepted answer. I could edit it to make it better, but why do that when others have given solid answers below? Bottom line: scroll past this to a more fulfilling life. :)

<BAD-ANSWER>

One way is continual polling:

function checkMenu() {
    if (!menu_ready) {
        setTimeout("checkMenu();", 1000);
        return;
    } else {
        // menu_ready is true, so do what you need to do here.
    }
}

and...

<body onload="checkMenu();">

</BAD-ANSWER>

相关文章