无法通过JavaScript访问变量 - 范围错误?

时间:2011-09-27 02:17:57

标签: javascript scope

我在一个与此类似的单独.js文件中有一些数据:

data = new Object();
data['cat'] = ['Mr. Whiskers','Wobbles'];
data['dog'] = ['Toothy'];
data['fish'] = ['goldy','roose'];

function getStuff(info)
{
  var stuff = data[info.value];
  return stuff;
}

现在在另一个带有块的html文件中,我有类似的东西:

function theDrop(dynamic) {
  alert(getStuff(dynamic));
}

方框说undefined,为什么?

1 个答案:

答案 0 :(得分:3)

你传递给theDrop的是什么?如果你想调用.value,那么你需要传递整个对象,否则你会得到undefined

<强> Live Demo

var select = document.getElementById("selectme");

select.onchange = function(){
    theDrop(this);
}

data = new Object();
data['cat'] = ['Mr. Whiskers','Wobbles'];
data['dog'] = ['Toothy'];
data['fish'] = ['goldy','roose'];

function getStuff(info)
{
    var stuff = data[info.value];
    return stuff;
}

function theDrop(dynamic) {
    alert(getStuff(dynamic));
}