search

Home  >  Q&A  >  body text

javascript - In the for traversal loop, how to make the result alert after else pop up only once?

In a for loop, when the previous two if conditions are not met, the alert prompt box will pop up. Due to the traversal query, alert will pop up multiple times according to the number of arrays. Please tell me how to truncate this so that it only pops up once after judgment?

$(function(){
    var jsons = [
            {"id":"621234","info":"内容一"},
            {"id":"62123456","info":"内容二"},
            {"id":"624321","info":"内容三"},
    ]

    function f(jsons,num) {
        var num8 = num.substr(0,8);
        var num6 = num.substr(0,6);
        var result6 = '';
        var result8 = '';
          for(var i = 0,len = jsons.length; i < len;i++) {
              var id = jsons[i].id;
              if(id == num8) {
                  result8 = jsons[i].info.toString();
                  $("#card_info").fadeIn("500");
                  $("#close").fadeIn("500");
                  break;
              }
              if(id == num6) {
                  result6 = jsons[i].info.toString();
                  $("#card_info").fadeIn("500");
                  $("#close").fadeIn("500");
              }
              else{
                alert("不符合条件");
              }
           }
          return result8 ? result8 : result6;
    }

    $("#down").click(function(){
      var user_info = $("#txt").val();
      var table = document.getElementById("card_info");
      table.innerHTML=(f(jsons, user_info));
    })

});

Currently, the pop-up window will pop up three times according to the number of json data. . .

黄舟黄舟2748 days ago1058

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-05-19 10:42:28

    function f(jsons, num) {
        var num8 = num.substr(0, 8);
        var num6 = num.substr(0, 6);
        var result = '';
        var inArr = 0;
        for (var i = 0, len = jsons.length; i < len; i++) {
            var id = jsons[i].id;
            if (id == num8) {
                result8 = jsons[i].info.toString();
                $("#card_info").fadeIn("500");
                $("#close").fadeIn("500");
                inArr++;
                break;
            }
            if (id == num6) {
                result6 = jsons[i].info.toString();
                $("#card_info").fadeIn("500");
                $("#close").fadeIn("500");
                inArr++;
            }
        }
        !inArr && alert("不符合条件");
        return result8 ? result8 : result6;
    }

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:42:28

    else if()

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:42:28

    Place it outside the for loop, and the alert will only occur when the values ​​of result8 and result6 are both empty.
    Why not break when id==6;?

    reply
    0
  • Cancelreply