我有以下课程,我希望创建一系列实例:
function rashnik(size, name) {
var img = document.createElement('img');
img.src = "pics/"+name+".jpg";
img.height = size;
img.width = size;
img.id = name;
d = 300-size;
img.style.marginBottom = d/2;
img.style.marginLeft = 50;
var gal = document.getElementById("gallery");
gal.appendChild(img);
};
现在,我创建了这个函数来创建实例:
function creater(names) {// the argument "names" would be a two-dimensional array
for (var a = 0; a < names.length; a++){
var names[a][0] = new rashnik(names[a][1], names[a][0]); // right here is where I get the error
}
}
这就是我试图称之为:
var friends = [["adi","300"],["tom","200"],["sleg","100"],["dorc","50"],["dork","25"]];
creater(friends);
问题是,var names[a][0]
部分抛出了一个错误,我完全理解;我想创建一个名称与names[a][0]
中存储的字符串相同的对象,但是,它只是不起作用。
有没有人知道我能做些什么来实现呢?
答案 0 :(得分:1)
清理干净。我认为这是你想要的:
resultsView['adi']
在下面的代码中的警报中访问了该内容,但也可以resultsView.Adi
function rashnik(size, name)
{
var img=document.createElement('img');
img.src = "pics/"+name+".jpg";
img.height = size;
img.width = size;
img.id = name;
d = 300-size;
img.style.marginBottom = d/2;
img.style.marginLeft = 50;
var gal = document.getElementById("gallery");
gal.appendChild(img);
this.img = img;
return this;
};
function creater(names)
{//the argument "names" would be a two-dimensional array
var results = { };
for(var a=0; a<names.length; a++)
{
results[names[a][0]] = new rashnik(names[a][1], names[a][0]);
}
return results;
}
var friends = [["adi","300"],["tom","200"],["sleg","100"],["dorc","50"],["dork","25"]];
var resultsValue = creater(friends);
alert(resultsValue['adi'].img.src);