for循环中生成的警报太多

时间:2014-11-12 08:21:25

标签: javascript json for-loop

我正在尝试为json酒单清除葡萄酒,如果json文件中不存在葡萄酒,我想弹出警报。但是列表中的每个i都会弹出警报。无法想出一种方法,可以在if语句转到else之前完成它。

function slettVin(){
    var slettInput = document.getElementById('slettInput');
    var slettInput_v = slettInput.value;
    for(wine=0; wine<dataHent.wines.length; wine++){
        if (dataHent.wines[wine].catalog == slettInput_v){
            dataHent.wines.splice(wine,1);
            var request = new XMLHttpRequest();
            request.open("POST","writeWine.php",false);
            request.setRequestHeader('Content-type','application/x-www-form-urlencoded');
            request.send("wines="+JSON.stringify(dataHent));
            fjernDiv();
            spesieltValg();
            slettInput.value ='';
            break;
        }
        else {
            alert('This wine doesnt exist');
        }
    }
}

1 个答案:

答案 0 :(得分:2)

在完成整个循环之前,您无法判断葡萄酒是否存在。使用变量来判断您是否找到了葡萄酒。

&#13;
&#13;
var dataHent = {
  wines: [{
    catalog: "aaa"
  }, {
    catalog: "bbb"
  }, {
    catalog: "ccc"
  }]
};

function slettVin() {
  var slettInput = document.getElementById('slettInput');
  var slettInput_v = slettInput.value;
  var wine_found = false;
  for (wine = 0; wine < dataHent.wines.length; wine++) {
    if (dataHent.wines[wine].catalog == slettInput_v) {
      dataHent.wines.splice(wine, 1);
      alert("Wine found, sending AJAX");
      slettInput.value = '';
      wine_found = true;
      break;
    }
  }
  if (!wine_found) {
    alert('This wine doesnt exist');
  }
}
&#13;
<input id="slettInput" type="text">
<button onclick="slettVin()">Click</button>
&#13;
&#13;
&#13;