我正在尝试基于通过AJAX从PHP脚本获得的列名以及预定义的列详细信息数组来构建表单。我希望将这些预定义的属性分配给传入的列并构建一个表单。例如,如果我曾经获得“ 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句