嗨我想改变一个函数内的全局变量,但它似乎并没有这样工作。这是我的JS:JavaScript中的全局变量在函数内改变
var currentImg = 0;
var totalImg = 0;
var stored_year = 0;
var newYear = 0; //the variable i want to edit
$("a.work").click(function(){
var newYear = $(this).html(); // how I want it to be edited
console.log(newYear);
});
$("#next-button").click(function() {
if (currentImg == totalImg) {
currentImg = 0;
}
else {
currentImg++;
}
changeImg();
});
$("#previous-button").click(function() {
if (currentImg == 0) {
currentImg = totalImg;
}
else {
currentImg--;
}
changeImg();
});
function changeImg(galleryYear) {
if (galleryYear === stored_year) {
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
}
else {
currentImg = 0;
$("#gallery-image").html("<img src='" + galleryYear.x_src[currentImg] + "'>");
$("#gallery-title").html(galleryYear.x_title[currentImg]);
$("#gallery-medium").html(galleryYear.x_medium[currentImg]);
$("#gallery-size").html(galleryYear.x_size[currentImg]);
$("#gallery-date").html(galleryYear.x_date[currentImg]);
var userCurrent = currentImg + 1;
var userTotal = galleryYear.x_id.length;
$("#current-post").html(userCurrent);
$("#post-total").html(userTotal);
var galWidth = $("#gallery-image" > "img").width();
$("#gallery").width(galWidth);
$("#gallery-type").html('<img id="gallery-switch" alt="Kyle Breitenbach Art Gallery Icon" src="images/gallery-icon.png" onClick="gallerySwitch('+window.newYear+')">');
stored_year = galleryYear;
}
}
t = 100;
d = 50;
function gallerySwitch(newYear){
$("#gallery-control-bar").fadeOut(t);
$("#gallery-image").fadeOut(t);
$("#info").fadeOut(t);
$(".gallery-viewer").fadeOut(t);
$('div.'+newYear).delay(t+d).fadeIn(t); // still not returning a number
} // other than 0.
function switchBack(){
currentImg = parseInt($(this).attr('id'));
alert(currentImg);
$(".gallery-viewer").fadeOut(t);
$("#gallery-control-bar").delay(t+d).fadeIn(t);
$("#gallery-image").delay(t+d).fadeIn(t);
$("#info").delay(t+d).fadeIn(t);
}
var navB = 0;
$("#mobileNav").click(function() {
if (navB == 0) {
$("#mobileMenu").fadeIn(t);
navB++;
}
else {
$("#mobileMenu").fadeOut(t);
navB--;
}
});
$(document).ready(function() {
changeImg(galleryYear);
});
如何使变量从一个函数内全局?
从函数中的变量中取出'var'。 – j08691