So I have a simple jQuery script running. It has 2 buttons, 1 that sends data, and 1 button needs to set the value of one of the variables send in the first one.
Ok so here is the script for button 1 (called p开发者_运维百科review):
$('#execute').click(function() {
$('#currentImage').remove();
$.ajax({
type: "POST",
url: "effect.php",
data: { action: $("[name='action']:checked").val(), source: sourceImage, destination: destinationImage, variables: $('#variables').val() },
success: function(msg){
$('#workspace').html(msg);
$("#preview").attr("src", destinationImage+"?timestamp=" + new Date().getTime());
}
}); });
What this does is put an effect to an image and it all works wonderfull. One of the first lines of the javascript contains the "sourceImage" variable.
var sourceImage = '20101201161609.jpg';
That variable is correctly passed to the script above. A second button (called Save State) makes sure that ones I feel happy with the effect of the image I save the state of the image, and continue with effects over that image. This means the source image needs to be changed, which I use the following script for:
$('#save_state').click( function() {
var sourceImage = '2010-12-02-35-20-preview.png';
$('#header').html(sourceImage); });
I left the line $('#header').html(sourceImage);
in to check if it was indeed triggered, and it was, so this line is not neccesary, but I know for sure that the action is triggered.
However, ones I again click on "Preview" in changes the value of variable sourceImage back to the value it started with, while it actually needs to keep this new value.
HOpe there's somebody that can help me.
By using the var
keyword you declare a local variable in the function, that is separate from the global variable with the same name. Remove the var
keyword to access the global variable:
$('#save_state').click( function() {
sourceImage = '2010-12-02-35-20-preview.png';
$('#header').html(sourceImage);
});
The sourceImage
variable in the second function is scoped locally to the function and doesn't refer to the same variable. I think you can make it work the way you want by simply removing the var
keyword. Having said that, you should be very careful using globally scoped variables. Generally you want to scope the variable as narrowly as possible. You might want to use the data
function to store this value in the DOM instead, though it's hard to know without more understanding of what you are trying to do.
Here...
$('#save_state').click( function() {
var sourceImage = '2010-12-02-35-20-preview.png';
$('#header').html(sourceImage); });
...you are doing absolutely nothing, because you are setting the local (as indicated by var
) variable sourceImage which goes out of scope immediately. The global (window) variable sourceImage remains untouched.
精彩评论