从头开始在正文中定义警报变量

Alert variable defined in body from head

本文关键字:变量 定义 正文 从头开始      更新时间:2023-09-26

我有一个简单的HTML页面,它使用了Facebook Javascript SDK:

<html>
 <head>
 <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
 <script>
 alert(publish);
 </script>
 </head>
 <body>
 <script type="text/javascript">
 window.fbAsyncInit = function() {
    FB.init({
       appId      : 'xxxxxxxxxxx',
       xfbml      : true,
       version    : 'v2.1'
    });
    FB.getLoginStatus(function(response) {
    });
    FB.api(
       "/me/permissions",
       function (response) {
          if(response && !response.error) {
              publish = '1';
          }
          else {
              publish = '0';
          }
       }
    );
 };
 (function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk')); 
 </body>
</html>

我想使用在FB.api函数中定义的名为publish的变量。我想在小节中使用它,但因为它是稍后定义的,所以它记录了一个未定义的变量错误。有办法绕过这个吗?

这里有两个问题,一个声明问题和一个时间问题。

截至您的alert行,尚未创建名为publish的变量。如果您尝试读取未声明符号的值,则会导致ReferenceError。(如果你试图写入一个未声明的符号,在宽松模式下你会得到隐式全局变量的恐怖,在严格模式下你就会得到一些合理的东西:ReferenceError。)

但更重要的是,时间问题:当你试图提醒它时,publish不仅未声明,而且即使声明了它,它也没有有用的值,因为你还没有设置值。

提醒publish值的正确位置是在api回调中,在那里您可以获得值:

FB.api(
   "/me/permissions",
   function (response) {
      var publish;                      // <== declare it
      if(response && !response.error) {
          publish = '1';
      }
      else {
          publish = '0';
      }
      alert(publish);                   // <== use it
   }
);

如果您需要在api回调之外使用publish,那么您可以将声明移动到回调之外。但是,在回调发生之前,您不能使用publish(有意义)。例如:

var publish; // <======= Declaration
window.fbAsyncInit = function() {
    FB.init({
       appId      : 'xxxxxxxxxxx',
       xfbml      : true,
       version    : 'v2.1'
    });
    FB.getLoginStatus(function(response) {
    });
    FB.api(
       "/me/permissions",
       function (response) {
          if(response && !response.error) {
              publish = '1';               // <=== fill it in
          }
          else {
              publish = '0';               // <===
          }
       }
    );
};
function doSomethingWithItLater() {        // <=== A function that uses it
    if (publish) {
        // Do this
    } else {
        // Do that
    }
}
(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk')); 

重要的是,在之后调用api回调并设置publish的值之前,不要调用doSomethingWithItLater。确保这一点的最佳方法是从回调中调用它。

您需要在函数启动之前定义变量。然后函数将更新变量。

<script type="text/javascript">
var publish;