如何从封装的.each函数中突破主要功能?

时间:2019-03-08 02:09:48

标签: javascript jquery

注意 :建议的问题并非完全相同,但其中的一个答案确实提供了解决方案。

我带注释的代码如下:

function AddMedRow(brand, generic, dose, doseunits, freq, durn, durnunit, instrn) {
    $(".DrugRow").each(function () {
        id = $(this).attr('id');            
        count = Number(id.replace("DrugRow", ""))            
        // If this row is empty, can add here
        if ($("#brand" + count).val() == "" && $("#generic" + count).val() == "") {
            $("#brand" + count).val(brand)                
            // I actually want to return true and break out of AddMedRow
            return true
        }
    });        
    // Some other code continues here, but should not execute once the if block in .each is true
}

编辑:我检查了以下代码:

function AddMedRow(brand, generic, dose, doseunits, freq, durn, durnunit, instrn) {
    dontiterate = false
    $(".DrugRow").each(function () {
        id = $(this).attr('id');
        console.log("id is " + id);
        // If this row is empty, can add here       
        count = id.replace("DrugRow", "");
        count = Number(count)
        if ($("#brand" + count).val() == "" && $("#generic" + count).val() == "") {
            $("#brand" + count).val(brand)
            dontiterate = true
            console.log("Let's see if we can break out without a control variable")
            return false
        }
    });
    if (dontiterate) {
        console.log("Not iterating because we are checking a control variable.")
        return true
    }
}

结果:

id is DrugRow1
Let's see if we can break out without a control variable
Not iterating because we are checking a control variable.

这意味着从.each内部返回true或false不会执行任何操作。您需要使用控制变量或标志

0 个答案:

没有答案