简体   繁体   English

如何在两个单独的函数中使用JavaScript变量?

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

I have the following jquery function 我有以下jQuery函数

$(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. 鼠标悬停时,我将#mainImageBrowser的内容复制到变量imageBrowserContent ,然后执行Ajax函数,该函数替换#mainImageBrowser的html内容,然后向我提示内容。 All of that works. 所有这些都可以。

My intent was to then replace #mainImageBrowser with the original contents, which would be stored in imageBrowserContent . 我的意图是然后将#mainImageBrowser替换为原始内容,该内容将存储在imageBrowserContent I couldn't get this to work, so I put alert(imageBrowserContent); 我无法使它正常工作,所以我设置了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. imageBrowserContent是第一个函数的局部变量。 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);
    })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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