如题,这就是朋友周末发的2个坑之一。 朋友有段ajax 去后端拿data,然后回填一堆 checkbox,然而貌似总是填错。debug 了半天,发现原来ie 会自动记录 checkbox.checked,autocomplete="off" 并没有什么用。
这坑的难度在于我debug + google 了半天才发现ie 有这个FEATURE (森气)!!
发现之后解决其实很简单了,就是 onload 的时候先把所有 checkbox 清空,然后再按照后端来的data 填
<script type="text/javascript">
window.onload = function () {
clearCheckboxValueForIe();
setTimeout(function () {
// ajax, and then tick some checkboxes
}, 0);
}
// to fix IE bug "always remember checkbox's checked"
function clearCheckboxValueForIe() {
var userAgent = window.navigator.userAgent;
var isIe = (userAgent.indexOf('MSIE') > -1); // ie6~10
isIe = isIe || (userAgent.indexOf('.NET4.0C;') > -1); // ie6~11
if (isIe) {
var inputs = document.getElementsByTagName('input');
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].getAttribute('type') === 'checkbox') inputs[i].checked = false;
}
}
}
</script>