如何在 if 语句的范围内 运行 只提醒一次?

How to run alert only once within range in if statement?

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

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

如何声明一个全局变量默认为true,

当你执行警报时将其设置为 false。

并将其添加到您的 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...");
  });
 }
}

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

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

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>

我 运行 你的代码和它 实际上工作正常 - 所以可能的原因是你再次 运行 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>