我正在尝试根据从 PHP 脚本通过 AJAX 获取的列名称以及预定义的列详细信息数组来构建一个表单。我希望将这些预定义的属性分配给传入的列并构建一个表单。例如,如果我得到“UserName”列,我希望始终成为 < input >
模板
var template = {
UserName : {
label: "User Name:",
type: "input"
}
UserId : {
label: "User Id:",
type: "text"
}
}
来自 AJAX 请求的传入 JSON 数组
{"UserName":"bob", "UserId":"1"}
现在我需要以某种方式“匹配”这些。我自己也不确定在这里要做什么。
$.each(data, function(i,e){
// if index (such as UserName) is found in template array, maybe add the attributes to it?
});
最佳答案
对于您的情况,使用 obj.hasOwnProperty(key) 来测试它是否存在,连接字符串并使用三元赋值来构建输入元素。如果您愿意,还可以使用 if 语句。
var $html = '';
$.each(data, function(idx,v){
$html += template.hasOwnProperty(idx)? '<input type="'+template[idx]['type']+'" name="'+idx+'"/>': '';
});
console.log($html);
关于javascript - 从数组分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26704365/