0

当满足特定条件(两个字符串相互匹配)时,我想调用一个函数(显示一个模式)。条件发生变化并在 for 循环中设置(它循环两个 JSON 文件的元素)。

可能的条件有以下三种:

1)没有输入字符串,没有匹配,没有问题;

2)我输入一个字符串:for循环循环告诉我字符串不匹配;

3) 我输入一个字符串:for 循环告诉我字符串匹配。

第二个和第三个条件是有问题的,因为它们在 for 循环循环中,我需要为它们中的每一个调用一个特定的操作,避免在满足条件 2) 时对循环中的每个元素重复该操作。

我想设置一个布尔标志,但我不确定我应该如何使用它。我在 for 循环外创建了一个变量,并给它赋值“false”。在 for 循环中,我通过给它赋值“true”来回忆这样一个变量。在第二个 for 循环之外,我在 if 语句中调用它,该语句调用一个函数来显示模态。

我写了以下代码:

function validateCitta() {
    $("#cercaCitta").prop("disabled", false);        
    let text = $('#inlineFormInputCitta').val();
    if (text === "") {
        $("#errorLog").show();
    }
    else {   


        var check = false;    //  I set the flag variable 


        $.ajax({
            url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
            dataType: "json",
            success: function (data) {
                for (let i = 0; i < data.features.length; i++) {
                    let typeCity = data.features[i].properties.geocoding.type;
                    if (typeCity === "city") {
                        let nameCity = data.features[i].properties.geocoding.name;
                        for (let i = 0; i < json.tappe.length; i++) {
                            let tappa = json.tappe[i];
                            let city = json.tappe[i].city;
                            if (city === nameCity) {
                                console.log("JSON file has been activated");


                                check = true;  // the condition 3 is fulfilled, then I perform the action below:

                                $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");                                    
                            }    
                            else if (check){     // the condition 3 is false, the condition 2 is fullfilled, then I show the Modal:
                                $('#myModal').show();
                            }    
                            ;
                        }                           
                        ;
                    }
                }
            }
        })           
    }
};

设置和调用布尔标志的正确方法是什么?您能否向我展示一些示例以更好地理解此类特定变量的用法以及从头开始使用它与在循环内使用它之间的区别?

4

0 回答 0