我有大约 100 个 PC 规范 下拉列表,如下所示:
<select class="drpProcessor spec-gen" name="processor_id">
<option value=""></option>
<option value="23">Some Processor</option>
</select>
我想要实现的是整个规范的对象(即所有 100 个规范下拉列表及其在一个对象中的值),如下所示:
var specs = {
processor_id : 21,
ram_id : 34,
motherboard_id: 45,
...
...
};
我知道我可以使用类似以下的方法实现此目的:
var specs = {
processor_id : $('.drpProcessor').val(),
ram_id : $('.drpRam').val(),
motherboard_id: $('.drpMotherBoard').val(),
...
...
};
但这将是一项乏味的工作(因为我必须为 100 个下拉菜单编写此代码)。幸运的是,我已将名称应用于每个我想作为各自规范属性的下拉列表。所以我继续写了这个小片段,它从每个下拉列表中取下了名称,并尝试将这个名称创建为 specs
对象的属性:
var els = $('#deassTab select');
// construct the specs object
var specs = {};
$(els).each(function( index, elem ){
specs.($(elem).prop('name')) = $(elem).val(); // <-- Problem Lies here
})
但它不允许我这样做并给出了这个错误:
SyntaxError: Unexpected token (
问题出在 specs.($(elem).prop('name'))
即我试图通过以下方式将此属性添加到 specs
对象字符串
。有什么方法可以实现这一点,即使用字符串创建对象的属性?
最佳答案
错误是行:
specs.($(elem).prop(name)) = $(elem).val();
当您想使用字符串动态设置属性时,您可以使用方括号语法(没有点)来制作该行:
specs[$(elem).prop(name)] = $(elem).val();
哪个应该可以解决您的问题。
关于Javascript - 使用字符串构造对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732622/