今天做项目需要将表单的HTML用jQuery替换以字符串的形式存入数据库,以下是本人写js脚本文件所整理的思路,仅供参考!
一、首先要将常用的HTML标签统一替换,如:select,input等
二、特殊的标签要做特殊处理,如input的单选,img图片等等
实例代码:
/**
* Created by bayayun on 2016/3/28.
* 模板替换
*/
function copyForm(el) {
/*获取表单的HTML代码*/
var form = $(el).html();
$('#hideWrap').html('');
$('#hideWrap').html(form);
$("input[name='_ajax']","#hideWrap").remove();
/*替换单选框*/
var rideo = $("input[type='radio']", el);
$("#hideWrap input[type='radio']").each(function (s){
var rad = $(rideo[s]).is(":checked");
if(rad){
/*删除当前节点除外的所有兄弟节点的父级节点*/
$(this).closest('label').siblings().remove();
$(this).closest('span').remove();
}
});
//console.log($('#hideWrap').html());
/*原表单值 处理input*/
var source = $('input', el);
$('#hideWrap input').each(function (i) {
var inputval = $(source[i]).val();
var type = $(this).attr('type');
/*如果input的type属性是隐藏就删除*/
if(type !== 'hidden'){
var str = '';
if (inputval != '') {
str += "<span>" + inputval + "</span>";
} else {
str += "<span> </span>";
}
$(this).replaceWith($(str));
}else{
$(this).remove();
}
});
//console.log($('#hideWrap').html());
/*原表单值 处理图片 获取显示值替换标签*/
$('#hideWrap .form-actions').remove();
/*处理联动select*/
$('#hideWrap .mcSelect').each(function(){
$(this).replaceWith($(this).html());
});
/*原表单值 处理select 获取select option:select 显示值*/
var seled = $('select option:selected', el);
var selects = $('select', el);
$('#hideWrap select').each(function (e){
var selval = $(selects[e]).val();
var sel = '';
if(selval){
var seledval = $(seled[e]).text();
if(seledval){
sel += "<span>" + seledval + "</span>";
}
}else{
sel += "<span> </span>";
}
$(this).replaceWith($(sel));
});
/*原表单值 处理textarea 获取显示值替换标签*/
var textar = $('textarea',el);
$('#hideWrap textarea').each(function (d){
var textval = $(textar[d]).val();
var texts = '';
if(textval){
texts += "<p>" + textval + "</p>";
}else{
texts += "<p> </p>";
}
$(this).replaceWith($(texts));
});
/*
*
* 循环遍历图片
* author wyh
* */
var imgval = '';
var imgstr = '';
$('#hideWrap .hiduploader img').each(function(){
if (typeof($(this).attr('alt')) !== 'undefined') {
imgval = $(this).attr('src');
if (imgval != '') {
imgstr = "<div class='thumbnail'> <img alt='"+$(this).attr('alt')+"' src="+imgval+" class='img-reponsetive'></div>";
} else {
imgstr = "<img alt='' src='/frame/public/assets/global/img/none.png' class='img-reponsetive'>";
}
$(this).closest('.hiduploader').html(imgstr);
}
});
var formhtml = $('#hideWrap').html();
$("input[name='formhtml']", el).val(formhtml);
}