在写表格排序的时候.大家经常会遇到.如果表格里有单选按钮或多选框.当你选中后. 如果表格排序后DOM重新添加.checked便会失效.
这是IE6和IE7下的BUG. IE8已经修复. 可在IE6 7下测试.
现象: 选中其它单选按钮 点击change后 会提示选中的还是默认的第一个.
解决方法: 在改变DOM结构前,将每个单选按钮的defaultChecked属性赋值.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body {font-size: 80%; line-height: 1.5}
body, button {font-family: arial;}
h1 { text-align: center }
div { border:1px solid #000; background-color: #FCF5B8; width: 100%; margin-bottom: 30px; }
#firstDiv { height: 80px; text-align: center;}
#secondDiv { height: 100px; text-align: center;}
#formP { font-size: 14px;}
</style>
</head>
<body>
<h1>IE6-7 Checked Bug</h1>
<div id="firstDiv">
<p><h3>1. Select radio to Checked<h3></p>
<p id="formP">
<form method="post">
<span id="radControl">
<input type="radio" name="rad" id="rad-1" value="rad-1" checked/><label for="rad-1">radio1</label>
<input type="radio" name="rad" id="rad-2" value="rad-2" /><label for="rad-2">radio2</label>
<input type="radio" name="rad" id="rad-3" value="rad-3" /><label for="rad-3">radio3</label>
<input type="radio" name="rad" id="rad-4" value="rad-4" /><label for="rad-4">radio4</label>
</span>
</form>
</p>
</div>
<div id="secondDiv">
<p><h3>2. Click button to change DOM structure</h3></p>
<p><button type="button" οnclick="changeDom()">Change</button></p>
</div>
<script type="text/javascript">
function getChkedRad() {
var rads = document.getElementsByName('rad');
for(var i = 0, len = rads.length; i < len; i++) {
if(rads[i].checked) {
return rads[i].value;
}
}
}
// 在更改DOM结构前 将所有的radio按钮的defaultChecked赋值.
function setRadDefaultVal() {
var rads = document.getElementsByName('rad');
for(var i = 0, len = rads.length; i < len; i++) {
rads[i].defaultChecked = rads[i].checked;
}
}
function changeDom() {
alert('Before change the checked radio is: ' + getChkedRad());
// 赋值defaultChecked
setRadDefaultVal();
var control = document.getElementById('firstDiv');
document.body.appendChild(control);
alert('After change the checked radio is: ' + getChkedRad());
}
</script>
</body>
</html>