1

我需要编写一个函数,在其中我可以在普通 js 中设置一个全局变量,用 jQuery 函数更新它的值,然后将通过 jQuery 函数更新的值分配给一个普通的 javasciprt 变量。

这是代码示例:

var foo; // global variable in plain js
var bar; // second global variable
jQuery(document).ready(function ($) { 

   // jquery function that updates the variable
   foo = 'updated by jquery' 

 });

bar = foo;

console.log(bar); // console should read 'updated by jquery' but it says undefined
4

3 回答 3

3

因为您正在更新foo唯一的,ready event但您要在准备好的火灾之前登录

尝试这个

jQuery(document).ready(function ($) { 
// jquery function that updates the variable
  foo = 'updated by jquery';
  console.log(foo);
});
于 2013-10-17T15:06:47.897 回答
2

它不会将值设置为“由 jquery 更新”,因为该更新将在文档准备就绪时发生,而您console.log(foo)是全局的一部分,它将在文档就绪函数调用之前按顺序发生。

所以,本质上,

var foo; // #1
$(function ($) { 
  foo = 'updated by jquery';
  console.log(foo); // output : updated by jquery //#3
});

console.log(foo); // output : undefined //#2

并且执行顺序是#1,#2,#3

因此,如果您需要更新的值,您需要在文档 .ready 中的第 3 点在更改后访问它。或者,您可以在使用 Jquery 事件更改值后引发/触发事件,例如 -

foo='updated';
var event = jQuery.Event( "myEvent" );
$('body').trigger(event);

// The following can now be outside of document ready
$('body').on('myEvent',function(){
   // Access updated foo value here
});
于 2013-10-17T15:08:54.733 回答
0

您的代码实际上应该可以正常工作。但是如果我们按顺序使用注释作为标记(所以 #2 = "//更新变量的 jquery 函数"),请记住它会按照 [#1, #3, #2] 的顺序运行,因为准备好了() 函数将在文档准备好时在其他函数之后运行。

只要任何需要 foo 的代码在您的 ready 函数之后运行,它就应该正确读取它。

于 2013-10-17T15:08:50.297 回答