JavaScript全局变量无法正常工作? [英] Javascript global variable not working properly?

查看:111
本文介绍了JavaScript全局变量无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的jQuery代码:

My jQuery code:

$(document).ready(function() {
    chrome.extension.sendRequest({get: "height"}, function(response) {
        height = response.value;
    });

    $("#id").css("height", height+"px");
});

您不必担心chrome.extension.sendRequest(),基本上它与背景页面进行通信以从localStorage获取"height"的值,并将该值存储在全局变量height中.

You don't have to be concerned about the chrome.extension.sendRequest(), basically it communicates with a background page to fetch the value for "height" from localStorage and stores the value in global variable height.

问题出在$("#id")没有分配高度值.但是,如果我将其修改为现在:

The problem lies in $("#id") not being assigned the height value. However if I were to modify it such that it is now:

$(document).click(function() {
    $("#id").css("height", height+"px");
});

有效.知道为什么吗?

推荐答案

原因是,当您将分配推迟到文档单击时,这意味着请求有时间完成,并设置高度值.

The reason is that when you defer the assignment to document click, that means the request has time to finish, and set the height value.

在您的第一个示例中,高度在分配时没有值.原因是传递给sendRequest的函数体不会立即执行,但会保存直到请求完成.之后,该函数被调用.但在此之前,javascript将继续执行您的$("#id")...语句.要确保只有在分配了一个值之前,才将其赋值,将其更改为以下内容:

In your first example, height doesn't have a value at the time of assignment. The reason is that the function body passed to sendRequest is not executed immediately, but it is saved until the request is finished. After that, the function is called. But before that, javascript will continue to execute your $("#id")... statement. To make sure that it is not assigned a value until there is one, change it to the following:

$(document).ready(function() {
    chrome.extension.sendRequest({get: "height"}, function(response) {
        height = response.value;
        $("#id").css("height", height+"px");
    });
});

现在,如果传递给sendRequest的回调函数在无法执行该代码的上下文中执行(浏览器扩展很可能就是这种情况),则可能必须将引用传递给该对象:

Now, if the callback function passed to sendRequest is executed in a context where that code cannot be executed, as may well be the case with browser extensions, you might have to pass a reference to the object instead:

$(document).ready(function() {
    var myObj = $("#id");
    chrome.extension.sendRequest({get: "height"}, function(response) {
        height = response.value;
        myObj.css("height", height+"px");
    });
});

但是如果可以的话,我会选择第一个版本.

But I'd go with the first version if that works.

应用此功能后,调查是否仍然需要保持height全局变量...

When you've applied this, investigate whether you still need to keep the height variable global...

这篇关于JavaScript全局变量无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆