【发布时间】:2013-05-15 15:04:56
【问题描述】:
我正在编写一个函数来将 json 对象转换为表单,并将其附加到 DOM。
我的语法似乎不正确; chrome 开发工具在第 15 行给了我一个“Uncaught SyntaxError: Unexpected identifier”错误。
我正在尝试支持单选、复选框和标准文本或文本框等表单案例。我不确定如何区分收音机和复选框。
这是我目前所拥有的:
jQuery.fn.toForm = function(obj) {
var target = this;
var form = document.createElement("form");
form.setAttribute('method', "post");
form.setAttribute('action', "submit.php");
$.each(obj, function(key, value){
var inputCheckbox = $("<input type='checkbox' value='"+value+"' />");
var inputStandard = $("<input type='text' value='"+value+"' />");
if(typeOf value === 'boolean'){
inputCheckbox.attr("id", key).attr("name", key).appendTo("form");
form.append(inputCheckbox);
}
else {
inputStandard.attr("id", key).attr("name", key).appendTo("form");
}
target.append(form);
});
};
有什么建议吗?
【问题讨论】:
-
typeOf 应该是 typeof(小写 o),我认为您的 JSON 字符串中有错误,但您没有发布。
-
form.append 不存在,不应该是 form.appendChild 吗?
标签: javascript jquery json forms api