JavaScript imageObj & Scope
There is a nested function (a function inside a function) that looks something like this along with some tests that I added:
function addImage( ....., borderColor){
var height;
var width;
var imageObj = new Image();
alert(' just before inner function is: ' + borderColor);
imageObj.onload = function(){
alert(' just after inner function is: ' + borderColor);
The first alert shows the c开发者_运维百科orrect color, but the second alert is 'null'.
How can I get the variable borderColor inside of the nested function?
test case here it works fine for me
- Are you sure the second alert is the
alert(' just after inner function is: ' + borderColor);
part ? - Are you sure the variable
borderColor
is not used elsewhere ? - what browser are you testing on ?
declare the onload
first, but trigger the load by assigning the source after that, like wrapping the outer function around the inner function:
function addImage(src, borderColor)
{
var pic = new Image();
pic.onload = function () {
alert(' just after inner function is: ' + borderColor);
}
alert(' just before inner function is: ' + borderColor);
pic.src = src; //<-- this is what you need to set.
}
You could try something like this (JSFiddle):
function addImage(borderColor){
var imageObj = new Image();
alert(' just before inner function is: ' + borderColor);
imageObj.addEventListener("load", function() {
alert(' just after inner function is: ' + borderColor);
}, false);
imageObj.src = "http://www.google.com/intl/en_com/images/srpr/logo1w.png";
};
addImage("#000000");
精彩评论