复制表单HTML内容, 且同时复制表单的最新值

遇到一个小需求,
即得到一个页面某一块的html源码, 这段html中包涵了一个表单, 且表单的值是被编辑过的,
直接用innerHTML(或jquery的html()方法)即可得到, 但各个浏览器表现不统一,表单的值有的原始值, 有的是最新值所以写了下面一个小方法来搞定


<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<title>复制html</title>
<meta name="author" content="sanshizi" />
<style>
*{font-size:14px;}
body{padding:20px;height:500px;}
</style>
<script type="text/javascript" src="jQuery.js"></script>
</head>
<body onclick="get()">
<div id="data">
<input type="text" name="t1" value="1" />
<input type="text" name="t2" value="2" />
<input type="text" name="t3" value="3" />

<select name="age">
<option value="1">1</option>
<option selected value="2">2</option>
<option value="3">3</option>
</select>

<input type="checkbox" name="ha" value="fff" />
<input type="checkbox" name="ha" value="zzz" />
<input type="checkbox" name="ha" value="ccc" />
<input type="checkbox" name="ha" value="xxx" />

<input type="radio" name="dd" value="1" />
<input type="radio" name="dd" value="2" />
<input type="radio" name="dd" value="3" />
<input type="radio" name="dd" value="4" />

<textarea cols="40" rows="3">asdfasfsf</textarea>

</div>

<script>
function get(){
//搞定 type=text, 同时如果checkbox,radio,select>option的值有变化, 也绑定一下, 这里忽略button
$("input,select option").each(function(){
$(this).attr('value',$(this).val());
});


//搞定 type=checkbox,type=radio 选中状态
$("input[type='checkbox'],input[type='radio']").each(function(){
if($(this).attr('checked'))
$(this).attr('checked',true);
else
$(this).removeAttr('checked');
});

//搞定select选中状态
$("select option").each(function(){
if($(this).attr('selected'))
$(this).attr('selected',true);
else
$(this).removeAttr('selected');
});

//搞定 textarea
$("textarea").each(function(){
$(this).html($(this).val());
});

alert($('#data').html())
}
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值