0

我正在尝试编写一个循环通过 xml 文件的脚本。使用下面提供的代码,当在搜索字段中输入正确的值时,它会返回警报但不显示信息。但是,当我删除错误检查并保留最后一个 if 语句时,它会运行并显示在表单中输入的正确值。

function searchAStylist() {
        var StylistListXML = loadXML("StylistList.xml");
        var StylistListXML_root = StylistListXML.documentElement;
        var stylistInfo_array = StylistListXML_root.getElementsByTagName('stylistInfo');
        storedResults = new Array;
        var stlyist_ul = document.getElementById("stylist");
        var search_field_div_test = " ?=(?:.*?[A-Za-z]){2}";

        var search_field_div = document.getElementById("search_field").value.toLowerCase().split(/[ ,]+/).join(' ');
        //console.debug(parseName + " test");
        for (var i = 0 ; i < stylistInfo_array.length; i++) {

            var nameElement = stylistInfo_array[i].getElementsByTagName('Name')[0];

            var li_element = document.createElement('li');
            var h2_element = document.createElement('h2');
            var h4_element = document.createElement('h4');
            var h42_element = document.createElement('h5');

            var name_text = nameElement.firstChild.nodeValue.replace(/,/g, ' ');
            var parseName = $.trim(name_text).replace(/,/g, ' ');
            var firstName = parseName.split(' ').slice(-1).join(' ');
            var lastName = parseName.split(' ').slice(0, -1).join(' ');
            var fullName = firstName + " " + lastName;


            h2_element.appendChild(document.createTextNode(fullName));
            li_element.appendChild(h2_element);

            h4_element.appendChild(document.createTextNode(combinedPostalCode.toUpperCase()));
            li_element.appendChild(h4_element);

            h42_element.appendChild(document.createTextNode(country_text.toUpperCase()));
            li_element.appendChild(h42_element);

            if (search_field_div == null || search_field_div == '') {
                alert("Please enter a Stylist name(First/Last or Full name), or Postal Code or City");
                return false;
            }else if(!(fullName.toLowerCase().indexOf(search_field_div) != -1)){
                alert("No Stylist found with that criteria");
                break;
            }

            if (fullName.toLowerCase().indexOf(search_field_div) != -1) {
                console.debug(parseName);
                stlyist_ul.appendChild(li_element);
            }
        }//END OF FOR LOOP

    }//END OF FUNCTION
4

1 回答 1

0

这里的 break 语句会在遇到第一个不匹配的记录时立即中断循环,在大多数情况下,这可能是第一次迭代

else if(!(fullName.toLowerCase().indexOf(search_field_div) != -1)){
    alert("No Stylist found with that criteria");
    break;
}

要跳过当前迭代并移动到下一个迭代,continue使用语句

于 2013-10-01T19:30:03.193 回答