javascript - 如何退出each()循环并从外部函数提前返回?

标签 javascript jquery

如果满足特定条件,我会尝试从事件处理函数提前返回(如果所选的 id 已在我的问题列表中。)

但是我没有看到我期望的结果。

当条件满足时,我收到“我应该返回”消息,但我也收到“我还去这里吗?”信息。这仍然允许其余代码在此函数中执行。

my.test.on('click', '.question-tagging .add-question-type', function() {
            var questionIds = getSelectedQuestionIds();

            console.log("questionIDs = " + questionIds);
            var currentQuestions = $.each($('.question-list .question-item'), function () {                    
                console.log("Question ID = " + $(this).find('.remove-tag').data('questionid'));
                if (questionIds == $(this).find('.remove-tag').data('questionid'))
                {
                    console.log("I should return");
                    return;
                }                    
            });

            console.log("did i still go here?");

            // more code...
});

最佳答案

如您所见,从 each() 返回,并不是从 click 处理程序返回。如果您放弃 each() 而使用简单的 for 循环,您可以获得您想要的结果:

my.test.on('click', '.question-tagging .add-question-type', function() {
    var questionIds = getSelectedQuestionIds();

    console.log("questionIDs = " + questionIds);
    var currentQuestions = $('.question-list .question-item');

    for ( var i = 0; i < currentQuestions.length; ++i )
    {
        var q = $(currentQuestions[i]);

        console.log("Question ID = " + q.find('.remove-tag').data('questionid'));
        if (questionIds == q.find('.remove-tag').data('questionid'))
        {
            console.log("I should return");
            return;
        }                    
    }

    console.log("did i still go here?");

    // more code...
});

关于javascript - 如何退出each()循环并从外部函数提前返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33176147/

相关文章:

jquery - 窗口变小时出现不寻常的空间

javascript - 加载带有 Bootstrap 模式的ajax页面,并立即自动启动该模式

javascript - 包含 .js 脚本的简单问题

javascript - 使用 $state.go 时,是否可以设置 onRouteParms Controller ?

Javascript sort() 不能正确按字母顺序排列

php - 将 PHP URL 变量传递给 jquery/ajax 表单

jquery - 我怎样才能告诉javascript在最大宽度之后执行

jquery - 使用 datatables.js 对格式为 #,###,###.## 的数字进行排序

javascript - 如何在 ServiceWorker 中处理 Session 过期

Javascript 验证 onkeypress 函数