简体   繁体   中英

How can I make use of a JavaScript variable across two separate functions?

I have the following jquery function

$(function(){

  $('.buttonEffectWrapper a').not('#browse-all a').hover(function(){

    pauseResume();
    var imageBrowserContent = $('#mainImageBrowser').html();
    $('#mainImageBrowserTabButtonWrapper, #slideshow > div')
      .animate({opacity:"0"}, {duration:250});

    ajaxFunction('footer');
    alert(imageBrowserContent);

  },
  function(){
    alert(imageBrowserContent);
  })

} );

On mouseover, I copy the contents of #mainImageBrowser to variable imageBrowserContent It then does an Ajax function which replaces the html content of #mainImageBrowser and then alerts me of what the contents are. All of that works.

My intent was to then replace #mainImageBrowser with the original contents, which would be stored in imageBrowserContent . I couldn't get this to work, so I put alert(imageBrowserContent); and no alert every pops up. What am I missing? If I put a text string in the alert, it popups fine, so I am confused...

After reformatting, the problem shows. imageBrowserContent is a local variable of the first function. It will not be visible inside the second function. If you move the variable declaration to the parent function, it will work.

$(function(){
    var imageBrowserContent;
    $('.buttonEffectWrapper a').not('#browse-all a').hover(function(){
        pauseResume();
        imageBrowserContent = $('#mainImageBrowser').html();

        $('#mainImageBrowserTabButtonWrapper, #slideshow > div')
            .animate({opacity:"0"}, {duration:250});
        ajaxFunction('footer');
        alert(imageBrowserContent);
    },
    function(){
        alert(imageBrowserContent);
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM