[英]How to stop a function if an alert is called?
我是JavaScript的初学者,正在为前一天在Meetup上学到的预编码练习中添加一些功能。 这是一种“虚拟宠物”,具有接受治疗,玩耍或锻炼的能力。 这些按钮的每次单击都会触发其重量或幸福感的递增或递减。 当这些值中的任何一个达到0时,就会发出警报,提示该宠物太瘦或太不开心...但是我仍然可以降低OTHER条件。 如果某人没有经验,那么最简单的方法是确保体重或幸福感达到0,这将引发警报并阻止您简单地单击“确定”并继续递减另一个?
这是我在CodePen中所做的工作: https ://codepen.io/HeyOliveHey/pen/wmGmRj
var pet_info = {
name: "Poodle",
weight: 45,
happiness: 4
}
$(function() {
// Called function to update the name, happiness, and weight of our pet in our HTML
checkAndUpdatePetInfoInHtml();
// When each button is clicked, it will "call" function for that button (functions are below)
$('.treat-button').click(clickedTreatButton);
$('.play-button').click(clickedPlayButton);
$('.exercise-button').click(clickedExerciseButton);
})
// Add a variable "pet_info" equal to a dictionary with the name (string), weight (number), and happiness (number) of your pet
function clickedTreatButton() {
pet_info.happiness = pet_info.happiness += 1;
// Increase pet happiness
pet_info.weight = pet_info.weight += 1;
// Increase pet weight
checkAndUpdatePetInfoInHtml();
}
function clickedPlayButton() {
pet_info.happiness += 1;
pet_info.weight -=1;
// Increase pet happiness
// Decrease pet weight
checkAndUpdatePetInfoInHtml();
}
function clickedExerciseButton() {
pet_info.happiness -=1;
pet_info.weight -=1;
// Decrease pet happiness
// Decrease pet weight
checkAndUpdatePetInfoInHtml();
}
function checkAndUpdatePetInfoInHtml() {
checkWeightAndHappinessBeforeUpdating();
updatePetInfoInHtml();
}
function checkWeightAndHappinessBeforeUpdating() {
if (pet_info.weight < 0) {
pet_info.weight = 0;
alert("Your dog is too skinny, feed it now.")
}
if (pet_info.happiness < 0) {
pet_info.happiness = 0;
alert("Your dog isn't happy, play with it or give it a treat.")
}
// Add conditional so if weight is lower than zero, set it back to zero
}
// Updates your HTML with the current values in your pet_info dictionary
function updatePetInfoInHtml() {
$('.name').text(pet_info['name']);
$('.weight').text(pet_info['weight']);
$('.happiness').text(pet_info['happiness']);
}
您可以使您的checkWeightAndHappinessBeforeUpdating()
函数返回一个值。 所以:
function checkWeightAndHappinessBeforeUpdating() {
var valid = true;
if (pet_info.weight < 0) {
valid = false;
pet_info.weight = 0;
alert("Your dog is too skinny, feed it now.")
}
if (pet_info.happiness < 0) {
valid = false;
pet_info.happiness = 0;
alert("Your dog isn't happy, play with it or give it a treat.")
}
return valid;
}
然后,您可以根据返回值进行决策。 因此在checkAndUpdatePetInfoInHtml
:
function checkAndUpdatePetInfoInHtml() {
if (checkWeightAndHappinessBeforeUpdating()) {
updatePetInfoInHtml();
}
}
您可以根据情况使用jQuery设置要禁用的相关按钮。
$(".exercise-button").attr("disabled", true);
因此,您将在警报后立即放置类似于此行的行,以禁用适当的按钮,然后您还需要在条件正确时也将它们设置为启用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.