Javascript global variable not working properly?

独自空忆成欢 提交于 2019-12-11 20:56:15

问题


My jQuery code:

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

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

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.

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");
});

it works. Any idea why?


回答1:


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.

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");
    });
});

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.

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



来源:https://stackoverflow.com/questions/2591814/javascript-global-variable-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!