变量未正确赋值,可能存在作用域问题(getJSON()中的each()中有一个开关的函数)
variable not being assigned correctly, possible scope issue (a function with a switch within each() within getJSON())
我有一个包含图像路径的变量。根据我接收到的JSON对象的整数值,这个变量应该得到不同的路径。
然而,由于某些原因,在下面的函数中,分配给变量的路径仍然是全局声明的路径,尽管我知道我的JSON对象为switch语句返回正确的整数。看看下面的代码:
function spawnThumbnails() {
$.getJSON('scripts/get_thumbs.php', function(data){
$.each(data, function(thumb, thumbInfo){
var thumbimage;
// If I create local thumbimage var like so,
//the image below turns is undefined
// But if local thumbimage var is not declared,
// the value defaults to globally declared value of arctic.svg
var thumbtype = thumbInfo.type;
alert(thumbtype); // this will alert correct type (an integer)
switch(thumbtype){
case 1: thumbimage = 'graphics/thumbs/arctic.svg'; break;
case 2: thumbimage = 'graphics/thumbs/savan.svg'; break;
case 3: thumbimage = 'graphics/thumbs/trop.svg'; break;
case 4: thumbimage = 'graphics/thumbs/tundra.svg'; break;
case 5: thumbimage = 'graphics/thumbs/ocea.svg'; break;
}
$("#thumbtest").append('<img src="' + thumbimage + '">');
// returning as the default image or undefined
}); //end each
}); // end json
}
var thumbimage = 'graphics/thumbs/artic.svg'; // default image
// I have tried placing the function definition here as well,
// but there is no difference. Should there be?
spawnThumbnails();
我是一种新的javascript函数作用域等。我认为我应该能够在函数调用和全局变量声明之前声明函数是对的吗?
我也觉得很奇怪,我不需要声明一个"thumbimage"参数在spawnThumbnails函数声明。事实上,如果我声明了一个参数,它就会中断。但我猜这是因为它创建了一个新的局部变量,对吗?
谢谢你的帮助!提前
交换机正在进行相同的比较(===
)。你的变量thumbtype
是一个字符串,即使它有一个数值,它仍然是一个字符串。
交换机正在计算'1' === 1
,由于类型不同,计算结果为false。
将其与字符串比较,而不是整数(注意引号)
switch(thumbtype){
case '1': thumbimage = 'graphics/thumbs/arctic.svg'; break;
case '2': thumbimage = 'graphics/thumbs/savan.svg'; break;
case '3': thumbimage = 'graphics/thumbs/trop.svg'; break;
case '4': thumbimage = 'graphics/thumbs/tundra.svg'; break;
case '5': thumbimage = 'graphics/thumbs/ocea.svg'; break;
}
或者将字符串转换为整数,并保留开关以数字进行比较。
thumbtype = parseInt(thumbtype);
来自ECMA 262语言规范,第12.11节:
如果input等于===操作符定义的clauseSelector,则
相关文章:
- 在jquery中等待getJSON完成的回调
- 如何在循环期间访问 jquery getJson 调用 ($.getJson) 中的索引变量
- 在另一个getJSON调用的回调中,没有为getJSON调用触发回调
- 将 .getJSON 中的表单附加到子元素
- 将“加载更多”添加到从Google电子表格中通过$.getJSON接收的数据输出中
- 如何从 .$getJSON 方法中的 jQuery 函数更新变量
- $.getJSON() 在 $.each() 循环中的调用未按顺序执行
- 在jquery中的getJson之后发布json数据
- while循环中的getJSON
- 全局变量未正确设置$.getJSON中的值
- 访问$.getJSON中的对象
- $.getJSON在Knockout.js中的URL错误
- $.getJSON竞赛条件中的$.each
- 变量未正确赋值,可能存在作用域问题(getJSON()中的each()中有一个开关的函数)
- $.getJSON() 中的代码不会被执行
- 将JSON数据传递到jQuery中的.getJSON
- 添加到getJSON中的数据
- 在. getjson()中传递相同参数的多个值
- 访问$. getjson中的DOM元素
- 如何使用$返回的变量.getJSON中的另一个函数