我有一个select标签,它有多个类别,其值为选项因此,当我从下拉列表中选择一个值时,我在select中获得相同的选项。但我的要求是在select标签中包含类别的值。
从选择选项
中选择法语1时的实际情况法语1
预期
法语 - 法语1
HTML
<select id="lang"></select>
Jquery的
var data = [
{
name: "English Languages",
values: ["English 1", "English 2", "English 3", "English 4"]
},
{
name: "French Languages",
values: ["French 1", "French 2", "French 3", "French 4"]
},
{
name: "Spanish Languages",
values: ["Spanish 1", "Spanish 2", "Spanish 3", "Spanish 4"]
}
];
for(var i = 0; i < data.length; i++) {
var category = data[i];
var optgroup = $("<optgroup>").prop("label", category.name);
for(var j = 0; j < category.values.length; j++)
optgroup.append($("<option>").text(category.values[i]));
$("#lang").append(optgroup);
}
答案 0 :(得分:2)
var data = [
{
name: "English Languages",
values: ["English 1", "English 2", "English 3", "English 4"]
},
{
name: "French Languages",
values: ["French 1", "French 2", "French 3", "French 4"]
},
{
name: "Spanish Languages",
values: ["Spanish 1", "Spanish 2", "Spanish 3", "Spanish 4"]
}
];
for(var i = 0; i < data.length; i++) {
var category = data[i];
var optgroup = $("<optgroup>").prop("label", category.name);
for(var j = 0; j < category.values.length; j++)
optgroup.append($("<option>").text(category.values[i]));
$("#lang").append(optgroup);
}
function changeData() {
var label = $('select :selected').parent().attr('label');
var selectedLang = $('select option:selected').text();
$('select option:selected').text(label + '-' + selectedLang);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lang" onchange="changeData()"></select>
&#13;
答案 1 :(得分:0)
您可以将第二个循环索引i更改为j(category.values [j])
var data = [
{
name: "English Languages",
values: ["English 1", "English 2", "English 3", "English 4"]
},
{
name: "French Languages",
values: ["French 1", "French 2", "French 3", "French 4"]
},
{
name: "Spanish Languages",
values: ["Spanish 1", "Spanish 2", "Spanish 3", "Spanish 4"]
}
];
for(var i = 0; i < data.length; i++) {
var category = data[i];
var optgroup = $("<optgroup>").prop("label", category.name);
for(var j = 0; j < category.values.length; j++)
optgroup.append($("<option>").text(category.values[j]));
$("#lang").append(optgroup);
}
function changeData() {
var label = $('select :selected').parent().attr('label');
var selectedLang = $('select option:selected').text();
$('select option:selected').text(label + '-' + selectedLang);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lang" onchange="changeData()"></select>