jquery中的html()方法可以轻易的获取innerHTML,但是在ie8和i火狐(还包括ie9,safari,谷歌浏览器)中,html()得到的值是不一样的。
下面是一个小例子,大家很容易看明白:
点击按钮以后的结果如下(注意画框的地方):
ie8中:
ie9,火狐中:
也就是说,FF下获得的HTML只有最原始的代码,不包括动态插入的内容。
纠结中......................纠结了好久.......................
大家不用纠结,有一个老插件可以解决这个问题,代码如下:
(
function
($) {
var oldHTML = $.fn.html;
$.fn.formhtml = function () {
if (arguments.length) return oldHTML.apply( this ,arguments);
$( " input,textarea,button " , this ).each( function () {
this .setAttribute( ' value ' , this .value);
});
$( " :radio,:checkbox " , this ).each( function () {
if ( this .checked) this .setAttribute( ' checked ' , ' checked ' );
else this .removeAttribute( ' checked ' );
});
$( " option " , this ).each( function () {
if ( this .selected) this .setAttribute( ' selected ' , ' selected ' );
else this .removeAttribute( ' selected ' );
});
return oldHTML.apply( this );
};
})(jQuery);
var oldHTML = $.fn.html;
$.fn.formhtml = function () {
if (arguments.length) return oldHTML.apply( this ,arguments);
$( " input,textarea,button " , this ).each( function () {
this .setAttribute( ' value ' , this .value);
});
$( " :radio,:checkbox " , this ).each( function () {
if ( this .checked) this .setAttribute( ' checked ' , ' checked ' );
else this .removeAttribute( ' checked ' );
});
$( " option " , this ).each( function () {
if ( this .selected) this .setAttribute( ' selected ' , ' selected ' );
else this .removeAttribute( ' selected ' );
});
return oldHTML.apply( this );
};
})(jQuery);
使用方法也很简单,就是替换html()为formhtml()。像这样:
function
getHTML(){
var val = $( " #mydiv " ).formhtml();
alert(val);
}
var val = $( " #mydiv " ).formhtml();
alert(val);
}
总结:
页面中输入的那个value,对DOM元素来说是个property,是不属于innerHTML里的IE8以下版本会出现,是因为IE不分attribute和property,这是IE的BUG,在IE9的时候终于得以修复而这个formHtml这个函数,强行给input元素加了一个叫value的attribute,从概念上说和dom的值value是不一样的,概念不同,不管怎么样,问题能解决就ok,不管是神马猫,能抓老鼠的猫就好好猫!