我不确定我的标题是否清晰,但让我们一起来看看。
我在li
列表中有2个ul
个元素,当我点击li
时,我想要获取li
的文本,然后创建一个对象基于phones
变量。
示例:当我单击NEXUS时,在控制台中获取一个具有属性的电话对象:
models: ['5', '6', '5X', '6P'];
不幸的是,我得到的是我无法将构造函数名称传递给函数setConstructor()
的返回值。我试着写" modelname"使用{}
和()
,但代码根本没有执行。
我该怎么做?
var phones = {
NEXUS: {
name: 'Nexus',
models: ['5', '6', '5X', '6P']
},
IPHONE: {
name: 'iPhone',
models: ['5', '5S', '6', '6S']
}
};
var lastConstructorClicked = {};
var output = {};
function Phone(constructorModels) {
this.models = constructorModels;
this.getModels = function () {
return this.models;
};
}
function setConstructor(modelname) {
return phones.modelname.models;
}
$("a[id^='show-models-']").click(function() {
lastConstructorClicked = $(this).text();
console.log(lastConstructorClicked);
output = new Phone(setConstructor(lastConstructorClicked));
});
console.log(output);

<ul class="dropdown-menu">
<li><a href="#" id="show-models-iphone">IPHONE</a></li>
<li><a href="#" id="show-models-nexus">NEXUS</a></li>
</ul>
&#13;
答案 0 :(得分:1)
phones.modelname.models
将查找成员实际命名为 modelname
,而不是该变量命名的成员。你想要:
phones[modelname].models
var phones = {
NEXUS: {
name: 'Nexus',
models: ['5', '6', '5X', '6P']
},
IPHONE: {
name: 'iPhone',
models: ['5', '5S', '6', '6S']
}
};
var lastConstructorClicked = "";
var output = {};
function Phone(constructorModels) {
this.models = constructorModels;
this.getModels = function() {
return this.models;
};
}
function setConstructor(modelname) {
return phones[modelname].models;
}
$("a[id^='show-models-']").click(function(e) {
e.preventDefault();
lastConstructorClicked = $(this).text();
console.log(lastConstructorClicked);
output = new Phone(setConstructor(lastConstructorClicked));
console.log(output);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="dropdown-menu">
<li><a href="#" id="show-models-iphone">IPHONE</a>
</li>
<li><a href="#" id="show-models-nexus">NEXUS</a>
</li>
</ul>
&#13;
答案 1 :(得分:0)
使用括号表示法访问对象
window.onload = function(){
var phones = {
NEXUS: {
name: 'Nexus',
models: ['5', '6', '5X', '6P']
},
IPHONE: {
name: 'iPhone',
models: ['5', '5S', '6', '6S']
}
};
var lastConstructorClicked = {};
var output = {};
$("a[id^='show-models-']").click(function() {
lastConstructorClicked = $(this).text();
console.log(lastConstructorClicked);
var output = phones[lastConstructorClicked].models;
console.log(output);
});
}
// plunk