解决标准浏览器下输入控件输入值或者选中状态不能通过innerHTML获取
标准浏览器下,输入控件输入内容(type=text或者textarea)或者更改过选中状态(select,radio,checkbox),通过容器的innerHTML并不返回当前输入的value值或者checked,selected状态(只返回页面初始化加载的html代码,就是查看源代码得到的html内容),IE浏览器下则可以通过innerHTML返回输入的值和选择状态。
如下DEMO
<div id="div"> <input type="text" /><input type="checkbox" /><input type="radio" name="r" /><input type="radio" name="r"/> </div> <input type="button" value="获取div的innerHTML" onclick="alert(document.getElementById('div').innerHTML)" />
输入内容,更改选中状态,IE下和标准浏览器(chrome,firefox等,非IE核心浏览器)输出如下
IE下下innerHTML包含了checked,value等属性,chrome和firefox没有包含。
解决办法:获取innerHTML代码前,重新设置输入控件的value,checked属性,对于select单选或者多选和textarea则需要自定义属性来保存默认的状态或者输入内容,然后再使用js读取自定义属性后设置textarea的值和设置select的option选中状态。
select增加value属性后并不能选中option,设置select option的selected属性innerHTML也返回不了option的selected属性,只好添加自定义属性selectedx来实现。
源代码如下
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <form id="f1"> <input type="text"> <select multiple id="ss"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <input type="radio" name="r1" value="1"/> <input type="radio" name="r1" value="2" /> <input type="radio" name="r1" value="3" checked /> <input type="checkbox" value="1"/> <input type="checkbox" value="2"/> <input type="checkbox" value="3"/> <textarea ></textarea> </form> <button onclick="alert(getHtml(true))">获取表单innerHTML</button> <button onclick="setHTML()">设置div的innerHTML,不做处理</button> <button onclick="setHTML(true)">设置div的innerHTML,处理数据并且设置状态</button> <div id="dv"></div> <script> function setHTML(process) { $('#dv').html(getHtml(process)); if (!window.ActiveXObject && process) { //处理标准浏览器下select对象的option选择问题 var arr, selector = '',i; $('#dv option[selectedx]').each(function () { $(this).attr('selected', true).removeAttr('selectedx'); }); //textarea有value属性没用,不会显示在输入框内,需要用js设置过value属性一次 $('#dv textarea').each(function () { $(this).val(this.getAttribute('value')); }); } } function getHtml(process) { if (window.ActiveXObject || !process) return $('#f1').html(); else {//标准浏览器,需要重新控件的value属性,要不返回容器的innerHTML输入的内容或者选择状态并不会通过innerHTML属性获取到 $($('#f1')[0].elements).each(function () { switch (this.tagName) { case 'INPUT': case 'TEXTAREA': switch (this.type) { case 'radio': case 'checkbox': if (this.checked) this.setAttribute('checked', true); else this.removeAttribute('checked'); //要记得删除,要不默认的选择会随innerHTML一起返回 break; default: this.setAttribute('value', this.value); } break; case 'SELECT': $('option', this).removeAttr('selectedx').not(':selected').removeAttr('selected').end().filter(':selected').attr('selectedx', 'selected'); break; } }); return $('#f1').html(); } } </script>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:解决标准浏览器下输入控件输入值或者选中状态不能通过innerHTML获取