jQuery.html()删除脚本和样式 [英] jQuery.html() removes scripts and styles

查看:255
本文介绍了jQuery.html()删除脚本和样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用jQuery.html(),而不松开脚本和样式?或任何其他非jQuery方式?

Is there a way to use jQuery.html() and not loose the scripts and styles? or any other non-jQuery way?

我试图输出用户所在页面的完整HTML。

I'm trying to output the full HTML of the page the user is on. Is this even possible?

推荐答案


jQuery.html()删除脚本和样式

jQuery.html() removes scripts and styles

这不是我的经验(见下文)。实际上,您必须注意,通过查询HTML字符串的DOM获取的内容总是为解释的 HTML,而不是原始的,并且会有奇怪的问题(例如, IE所有的HTML标签名称都是IN UPPER CASE)。这是因为jQuery的 html 函数依赖于浏览器的 innerHTML 属性,它会随浏览器的不同而有所不同。但下面的演示包括在Chrome 4,IE7和Firefox 3.6上的样式和脚本标签;

That isn't my experience (see below). In practice, you have to be aware that what you get back by querying the DOM for HTML strings is always going to be the interpreted HTML, not the original, and there will be quirks (for instance, on IE all the HTML tag names are IN UPPER CASE). This is because jQuery's html function relies on the browser's innerHTML property, which varies slightly browser to browser. But the demo below includes both style and script tags on Chrome 4, IE7, and Firefox 3.6; I haven't tried others, but I would expect them to be okay.

如果你想得到外部链接页面的内容以及内联的内容,你自然必须解析结果并按照 src (在脚本上), href (在链接 rel =stylesheet)等。

If you want to get the content of externally-linked pages as well as the inline content, you will naturally have to parse the result and follow the src (on scripts), href (on links that have rel = "stylesheet"), etc...

演示:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
(function() {
    $(document).ready(pageInit);

    function pageInit() {
        $('#btnGo').click(go);
    }

    function go() {
        alert($('html').html());
    }
})();
</script>
</head>
<body>
<input type='button' id='btnGo' value='Go'>
</body>
</html>

这篇关于jQuery.html()删除脚本和样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆