怎么完整的获取到网页中 的内容?
我们知道,在一个页面中,我们有时候需要获取某个指定标签下的内容(完整的html代码内容),js中提供了document.getElementById("divID").innerHTML;方法可以使我们获取到指定ID内的所有html代码,但是这往往不能满足我们的需求,当标签中有input或者textarea标签供我们输入内容是,这个时候用innerHTML方法只能获取到html的内容,不能获取到我们从键盘输入的信息。JQuery中的html()也提供了类似的方法,但是也不能满足我们的要求。
解决方法:
我们这个时候可以重写JQuery的方法来实现我们需要的操作。具体操作如下:
具体的代码:(定义一个div框,id为divID,下面定义一个butten按钮,当我们点击按钮时触发tijiao()方法来实现获取div框中的内容操作。)
<div id="divID">
姓名:<input type="text" name="name" />
型号:<input type="text" name="xinghao" />
规格:<input type="text" name="guige" />
</div>
<input type="button" value="提交" onclick="tijiao()" />
Js代码:
<script type="text/javascript">
function tijiao(){
var message = $("#divID").html();
alert("html获取的值:" + message);
}
</script>
重写之前的效果:
重写之后的js代码为:
<script type="text/javascript">
(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 () {
// im not really even sure you need to do this for "checked"
// but what the heck, better safe than sorry
if (this.checked) this.setAttribute('checked', 'checked');
else this.removeAttribute('checked');
});
$("option", this).each(function () {
// also not sure, but, better safe...
if (this.selected) this.setAttribute('selected', 'selected');
else this.removeAttribute('selected');
});
return oldHTML.apply(this);
};
//optional to override real .html() if you want
// $.fn.html = $.fn.formhtml;
})(jQuery);
function tijiao(){
var message = $("#divID").formhtml();
alert("html获取的值:" + message);
}
</script>
重写之后的效果: