2013-08-01 38 views
0

我有一些棘手的问题。我试图在下面的函数/循环中添加一个第三个参数,并且已经撞墙了。帮帮我?如何添加第三个变量到jQuery“each”函数?

​​

下面的代码是什么样子的studentselectValues变量:

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

我在做什么是填充与上面显示的选项的选择。我的目标是为每个选择添加一个第三个属性。有没有人有线索我会如何做到这一点?

在此先感谢。

回答

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)); 
}); 

Fiddle

-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)); 
} 

在一个旁注,你不应该追加循环中的每个项目:它的资源很大。连接,然后附加。

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); 
+0

为什么-1一个正确的答案? – pixeline

0

我推荐你用对象创建一个数组,然后你是否可以用你想要的来喂它。

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)); 
    }); 
相关问题