我在JS文件中有此代码:
function buildRolePicker() {
var pnl = $("[id$='staffRoles']");
$.each(roles["ContactGroupRoles"], function(iteration, item) {
pnl.append(
$(document.createElement("input")).attr({
id: 'cgr' + item['RoleId'],
name: 'cgroles',
value: item['RoleId'],
title: item['RoleName'],
type: 'checkbox'
})
);
pnl.append(
$(document.createElement('label')).attr({
'for': 'cgr' + item['RoleId']
})
.text(item['RoleName'])
);
});
alert(document.forms[0].cgroles[8].value);
}
我在代码的其他部分浪费了一些时间,试图找出为什么调用
alert(document.forms[0].cgroles[8].value);
正在返回值“on”,而它应该返回一个long。结果发现问题在于属性的定义顺序。如果我改变这个:
$(document.createElement("input")).attr({
id: 'cgr' + item['RoleId'],
name: 'cgroles',
value: item['RoleId'],
title: item['RoleName'],
type: 'checkbox'
})
对此:
$(document.createElement("input")).attr({
type: 'checkbox',
id: 'cgr' + item['RoleId'],
name: 'cgroles',
value: item['RoleId'],
title: item['RoleName']
})
一切正常,当我:
警报(document.forms[0].cgroles[8].value);
我的问题是为什么?
测试数据:
var roles = {"ContactGroupRoles":[
{"RoleId":1,"RoleName":"Pending"},
{"RoleId":2,"RoleName":"CEO"},
{"RoleId":3,"RoleName":"Financial Controller"},
{"RoleId":4,"RoleName":"General Manager"},
{"RoleId":5,"RoleName":"Production Manager"},
{"RoleId":6,"RoleName":"Sales Manager"},
{"RoleId":7,"RoleName":"Marketing Manager"},
{"RoleId":8,"RoleName":"Sales Agent"},
{"RoleId":9,"RoleName":"Customer Service"},
{"RoleId":10,"RoleName":"Manager"}
]};