我正在尝试创建接收div属性的代码,并将其内容替换为表单字段(根据属性)
我如何接收所有div DATA属性(即:数据类型。数据名称...)并将其转换为表单字段?
HTML
<form action='#' method='post' id="4" class='item'>
<div class='item-edit' data-type='fileArray' data-name='file[]' data-maxFiles='1'>LOGO HERE</div>
<div class='item-edit' data-type='input' data-name='agnt[name]' data-require='1'>SOME NAME</div>
<div class='item-edit' data-type='textarea' data-name='agnt[contact]'>SOME CONTACT</div>
<div class='col-md-2 panel-menu'>
<span class='edit_msg'></span>
<a href='#' class='btn btn-success edit_save-btn hidden'>SAVE</a>
</div>
</form>
<form action='#' method='post' id="5" class='item'>
<div class='item-edit' data-type='fileArray' data-name='file[]' data-maxFiles='1'>SECOND LOGO</div>
<div class='item-edit' data-type='input' data-name='agnt[name]' data-require='1'>SECOND NAME</div>
<div class='item-edit' data-type='textarea' data-name='agnt[contact]'>SECOND CONTACT</div>
<div class='col-md-2 panel-menu'>
<span class='edit_msg'></span>
<a href='#' class='btn btn-success edit_save-btn hidden'>SAVE</a>
</div>
</form>
JS代码
//此函数应获取属性的数据数组并返回表单字段(输入,文本区域等)
function convert_text_to_form_field ($data)
{
fieldValue = element.parents(".item_edit").text();
fieldName = element.parents(".item_edit").attr("data-name");
fieldType = element.parents(".item_edit").attr("data-type");
fieldRequire = element.parents(".item_edit").attr("data-require");
maxFiles = element.parents(".item_edit").attr("data-maxFiles");
switch(fieldType) {
case "input":
field = "<input type='text' name='"+fieldName+"' value='"+fieldValue+"' />";
break;
case "textarea":
field = "<textarea type='text' name='"+fieldName+"'>"+fieldValue+"</textarea>";
break;
case "fileArray":
field = "<input type='file' name='"+fieldName+"' class='multi well well-sm' maxlength='"+maxFiles+"' accept='gif|jpg|jpeg|png|bmp' />";
break;
};
if (fieldRequire = 1)
field = field + "<span>*</span>";
return (field);
}
//此函数应获取div属性并将其作为数组发送到函数“ convert_text_to_form_field”
$(document).on("click", ".edit-btn", function(e){
var element = $(this);
// clear msg box content
element.parents(".panel-menu").find(".edit_msg").text("");
element.parents(".panel-menu").find(".edit_msg").removeClass("fa fa-check text-success");
element.parents(".panel-menu").find(".edit_msg").removeClass("fa fa-close text-danger");
var data = $(element).parents(".item_edit").data();
var fieldContent = convert_text_to_form_field (data)
element.parents(".item").find(".item_edit").html(fieldContent);
});