如何在if语句的范围内仅运行一次警报?

时间:2019-02-13 04:47:41

标签: javascript jquery if-statement alert

function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100){
  $(".treat-button").one("click", function(){
    alert(petInfo.name + " is going obese...");
  });
 }
}

基本上,我想做的是在petInfo.weight等于或超过100时仅显示一次警报,并在每次单击treat-button之后停止警报。我试图寻找答案并尝试了所有可能的方法,但是它不起作用...请帮助我成为优秀的代码大师!

4 个答案:

答案 0 :(得分:1)

您可以创建一个变量并在显示警报之前检查其状态

let showAlert = true;
$(".treat-button").click(function() {
  if ((petInfo.weight >= 100 && previousWeight < 100) && showAlert) {
    alert(petInfo.name + " is going obese...");
    showAlert = false;
  }
});

答案 1 :(得分:0)

如何在默认情况下将全局变量声明为true,

在执行警报时将其设置为假。

并将其添加到您的if条件中。

var isAlertShown = true;

和您的功能

function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100 && isAlertShown){
  $(".treat-button").one("click", function(){
    isALertShown = false;
    alert(petInfo.name + " is going obese...");
  });
 }
}

答案 2 :(得分:0)

var alerted = false;

var previousWeight = 99

var petInfo = {
  weight: 101,
  name: 'petName'
}

$(".treat-button").one("click", function(){
  if(!alerted && petInfo.weight >= 100 && previousWeight < 100){
    alerted = true;
    alert(petInfo.name + " is going obese...");
  }
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<div class="treat-button" style="width: 100px; height: 100px; background-color: red;">TREAT</div>

答案 3 :(得分:0)

我运行您的代码,它实际上还不错-可能的原因是您在 按钮单击后再次运行sendWeightAlert()(这再次绑定了事件处理程序-并且下次点击后显示提醒)

let previousWeight= 10;
let petInfo = { weight: 100, name: 'dog' };

function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100){
  $(".treat-button").one("click", function(){
    alert(petInfo.name + " is going obese...");
  });
 }
}


sendWeightAlert();  // here we bind handler only once, and jQuery `one` will run it once.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="treat-button">click me</button>