不断地检查一个元素的长度,如果它是 1 就执行一个动作

Constantly check the length of an element and perform an action if it is ever 1

我一直在监视页面上的一个元素。如果在任何时候该长度等于 1,则表示它存在于页面上(用户已注销),我想通过弹出窗口提示他们登录。

所以现在我有这个:

function loginNotice() {
    //do prompt
}
keepAlive();

function keepAlive() {
    if($('.username_field').length == 1){
        loginUser();
    }
    try {
        setTimeout(function(){keepAlive();}, 10000);
    } catch (ex){
    }
}

我认为这不是很有效。因为它经常检查并在需要时运行提示。问题是页面可能会加载,长度可能已经是 1,也可能是 0。我不知道在任何给定时间它会是什么,所以我不能只做一个改变。

有什么方法可以更有效地做到这一点?

您可以在 parent/ancestor 节点上使用 mutation observer,观察 subtree and/or childList.

的变化
var ancestor = $("...closest ancestor that doesn't change..."); // Worst case, $('body')
var ob = new MutationObserver(function() {
    if($('.username_field').length == 1){
        loginUser();
    }
});
ob.observe(ancestor[0], {
    subtree: true,   // You probably only need...
    childList: true  // ...one of these or the other
});

话虽如此,但每 10 秒执行一次 DOM 查询根本不是问题;如果您不需要比这更快的反应,您当前的解决方案就可以了。