gpt4 book ai didi

javascript - 带有数组javascript的下拉列表选项值和名称

转载 作者:行者123 更新时间:2023-11-30 05:41:00 26 4
gpt4 key购买 nike

我在 javascript 中遇到数组问题。是否可以在同一个数组中插入名称和值

这是我的数组代码

press=new Array('T shirt black - $23','Sweater black - $34','Hoodie shirt black - $87');

这是我想要的输出

<option value="23">T shirt black - $23</option>

如何将“23”放入数组中?

这是完整的代码。如果我无法解释,请见谅

http://jsfiddle.net/V64hb/1/

http://pastebin.com/zyiQGHTS

最佳答案

您可以使用对象数组:

press = [
{ desc: 'T shirt black',
price: 23
},
{ desc: 'Sweater black'
price: 34
},
{ desc: 'Hoodie shirt black'
price: 87
}
];

然后您可以使用 press[i].descpress[i].price 访问它们。

press.forEach(function(item) {
$('#item').append($('<option/>', {
value: item.price,
text: item.desc+' - $'+item.price
}));
});

这是您的 fiddle 的完整重写。我还摆脱了 eval(),方法是将所有不同的数组放入一个以类别值作为键的对象中。

$(document).ready(function () {
dropdowns = {
web: [
{desc: "1 Custom Web Page", price: 39},
{desc: "5 Custom Web Pages", price: 190},
{desc: "10 Custom Web Pages", price: 375},
{desc: "20 Custom Web Pages", price: 710}
],
art: [{desc: '300-word Article x 1', price: 7.00},
{desc: '300-word Article x 5', price: 32.00},
{desc: '400-word Article x 1', price: 8.00},
{desc: '400-word Article x 5', price: 37.00},
{desc: '500-word Article x 1', price: 9.00},
{desc: '500-word Article x 5', price: 40.00},
{desc: '700-word Article x 1', price: 12.00},
{desc: '700-word Article x 5', price: 57.00},
{desc: '1000-word Article x 1', price: 15.00},
{desc: '1000-word Article x 5', price: 70.00}],
blog: [{desc: '300-word Custom Blog x 1', price: 10},
{desc: '400-word Custom Blog x 1', price: 12},
{desc: '500-word Custom Blog x 1', price: 14},
{desc: '300-word Custom Blog x 5', price: 47},
{desc: '400-word Custom Blog x 5', price: 55},
{desc: '500-word Custom Blog x 5', price: 63}
],
press: [{desc: '300-word Custom Press Release', price: 27},
{desc: '400-word Custom Press Release', price: 37},
{desc: '500-word Custom Press Release', price: 47}
]
}

populateSelect();

$(function () {
$('#cat').change(populateSelect);
});

function populateSelect() {
var cat = $('#cat').val();
$('#item').empty();

dropdowns[cat].forEach(function(item) {
$('#item').append($('<option/>', {
value: item.price,
text: item.desc+' = $'+item.price
}));
});
}

});

DEMO

关于javascript - 带有数组javascript的下拉列表选项值和名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com