jQuery中html()方法产生的问题

今天工作中需要用到这样一个效果:table里面排列着一些文本框,在输入数值以后,保存table的全部html元素,包括刚输入的数值。

这里用jquery的html()方法很容易实现。但是测试的时候发现,在ie8和i火狐(还包括ie9,safari,谷歌浏览器)中,html()得到的值是不一样的。

下面是一个小小的例子,我想大家很容易看明白:

View Code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
<script type="text/javascript" src="js/jquery.tools.min.js"></script>
<script>
function save(){
var content = $("#mytable").html();
alert(content);
}
</script>
</head>

<body>
<table width="100" border="0" cellpadding="0" cellspacing="0" id="mytable">
<tbody>
<tr>
<td><input type="text" name="textfield"></td>
</tr>
<tr>
<td><input type="button" name="Submit" value="保存" onClick="save()"></td>
</tr>
</tbody>
</table>
</body>
</html>

点击按钮以后的结果如下(注意我画框的地方):

ie8

ie9,火狐

 

也就是说,FF下获得的HTML只有最原始的代码,不包括动态插入的内容。这样就很纠结,我不希望这样。

至于为什么会这样,也许是火狐等浏览器的限制?我真的不知道,有待研究,哪位大侠能告诉我,感激不尽。

现在我只能尽快想办法解决这个问题,完成工作要求

 

搜索的百度,谷歌,找到一个老外写的插件,其实是很简单的一个方法,代码如下:

View Code
(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);

 

使用方法也很简单,就是替换html()为formhtml()。像这样:

View Code
function save(){
var content = $("#mytable tbody").formhtml();
alert(content);
}

 

结果大家可以自己试一试。

posted @ 2011-08-31 14:00  § 薄樱 §  阅读(13120)  评论(20编辑  收藏  举报