0

我有一个棘手的问题。我正在尝试将第三个参数添加到以下函数/循环中并且遇到了问题。帮助?

$.each(studentselectValues, function(key, value) {   
    $('select[name="cf_Student"]')
        .append($("<option></option>")
        .attr("value",key)
        .text(value)); 
});

以下是studentselectValues变量的代码:

studentselectValues = {
    '1': 'My 1st Option',
    '2': 'My 2nd Option',
    '3': 'My 3rd Option'
}

我正在做的是用上面显示的选项填充一个选择。我的目标是为每个选择添加第三个属性。有谁知道我将如何做到这一点?

提前致谢。

4

3 回答 3

5

studentselectValues会将散列变成一个散列数组......这样你就可以根据需要使用尽可能多的属性:

studentselectValues = [
    { id: '1', key: 'My 1st Option', text: 'First' },
    { id: '2', key: 'My 2nd Option', text: 'Second' },
];

$.each(studentselectValues, function(index, item) {   
    $('select[name="cf_Student"]')
        .append($("<option></option>")
        .attr("value",item.key)
        .text(item.text)); 
});

小提琴

于 2013-08-01T01:34:28.983 回答
0

I recomend you to make a array with objects, then are you possible to feed it with what you want.

   var studentselectValues = [
     { value: 1, label: 'test', extraattr: 'hoho' },
     { value: 2, label: 'test2', extraattr: 'test' }
   ];

  $.each(studentselectValues, function() {   
    $('select[name="cf_Student"]')
        .append($("<option/>")
        .val(this.value)
        .attr('data-id', this.extraattr)
        .text(this.label));
  });
于 2013-08-01T01:40:16.977 回答
-1
studentselectValues = [{
    {key:'1', value:'My 1st Option', third:"third value"},
    {key:'2', value:'My 2nd Option', third:"third value"},
    {key:'3', value:'My 3rd Option', third:"third value"}
}];

$.each(studentselectValues, function(index, data) {
$('select[name="cf_Student"]')
        .append($("<option></option>")
        .attr("value",data.key)
        .text(data.value+ " "+ data.third)); 
} 

On a sidenote, you shouldn't append each item in the loop: it's resource-heavy. Concatenate and then append instead.

var studentselectValues = [{
    value: '1',
    key: 'test',
    third: 'hoho'
}, {
    value: '2',
    key: 'test2',
    third: 'test'
}];
var options = [];
$.each(studentselectValues, function () {
    options.push('<option value="' + this.key + '">' + this.value + ' ' + this.third + '</option>');
});
var optionsS = options.join();
$('select[name="cf_Student"]').append(optionsS);
于 2013-08-01T01:38:28.213 回答