Javascript global variable not working properly?
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?
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...
精彩评论