我是 jQuery 的新手。我正在尝试创建一个全局变量,以便可以在页面之间传递它。但是,当我“警告”文档中的变量时,它是未定义的。
这是我创建全局变量 (modalHandler.js) 的脚本:
var remainingCal;
$(document).ready(function() {
$(document).on("click", "#modal-btn", function() {
$(".nav > li").first().next().remove();
//get form inputs and calc remaining calories
var gender = $("#gender").val();
var age = getAge();
var height = getHeight();
var weight = getWeight();
var goal = $("#loss-goal").val();
var activity = $("#activity").val();
remainingCal = calcDailyReq(gender, age, height, weight, activity, goal);
jQuery('<li/>', {
id: 'dashboard',
}).appendTo(".nav").append("<a href='dashboard.html'>Dashboard</a>");
var url = "dashboard.html"
window.location.replace(url);
});
});
function getAge() {
ageCode = $("#age").val();
var minAge = 18;
var age = parseInt(ageCode) + minAge;
return age;
}
function getHeight() {
var heightCode = $("#height").val();
var minHeight = 54;
var height = parseInt(heightCode) + minHeight;
return height;
}
function getWeight() {
var weightCode = $("#weight").val();
var minWeight = 100;
var weight = parseInt(weightCode) + minWeight;
return weight;
}
//Calculates daily calories using BMR, Harris Benedict Equation, and weight loss goal input
function calcDailyReq(gender, age, height, weight, activity, goal) {
var bmr;
var dailyReq;
var poundOfFat = 3500;
if (gender == "male") {
bmr = 66 + (6.23 * weight) + (12.7 * height) - (6.8 * age);
} else {
bmr = 665 + (4.35 * weight) + (4.7 * height) - (4.7 * age);
}
if (activity == "0") {
dailyReq = bmr * 1.2
} else if (activity == "1") {
dailyReq = bmr * 1.375;
} else if (activity == "2") {
dailyReq = bmr * 1.55;
} else if (activity == "3") {
dailyReq = bmr * 1.725;
} else {
dailyReq = bmr * 1.9;
}
var weeklyTarget = dailyReq - (poundOfFat * parseFloat(goal))/7;
return Math.round(weeklyTarget);
}
下面是我试图访问全局剩余Cal 变量的页面上的 html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Online Calorie Tracker and Analyzer</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/dashboard.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/modalHandler.js"></script>
<script src="js/dashboard.js"></script>
</head>
<body>
<div class="container">
<h1>Calorie Tracker and Analyzer</h1>
<div class="navbar">
<div class="navbar-inner">
<div class="container">
<ul class="nav">
<li><a href="index.html">Home</a></li>
<li class="active"><a href="dashboard.html">Dashboard</a></li>
</ul>
</div>
</div>
</div>
<div class="hero-unit">
<h3 id="track-head">Track What You Eat</h3>
</div>
</body>
<html>
dashboard.js 简单地包括:
alert(remainingCal);
这会在页面中产生 undefined 。任何帮助表示赞赏!