jQuery.html()未正确设置内容
jQuery .html() not setting content correctly?
下面是我准备的一个例子,可以更容易地讲述这个问题。
http://codepen.io/anon/pen/EVpYXm
如您所见,初始<html>
设置为显示文本:
"这是旧的html!"
它将整个内容设置为变量myHtml
中的数据。然而,我注意到:
样式不是从CCD_ 3元素携带的。此外,<body>
元素在某种程度上根本没有创建!
这是sring myHtml
,整理后显示为html:
<html>
<head>
<title>Title Here</title>
<link href='style.css' rel='stylesheet' type='text/css'/>
</head>
<body style='background-color: red'>
<div>Div!</div>
</body>
</html>
我已经意识到,当链接元素被删除时,一切都很好。试试看吧。
在过去的几个小时里一直被这个问题困扰着。正在寻找结果。
这是完整的代码:
页面html:
<html>
This is the old html!
</html>
javascript:
$(function(){
var myHtml = "<html><head><title>Title Here</title><link href='style.css' rel='stylesheet' type='text/css'/></head><body style='background-color: red'><div>Div!</div></body></html>"
$("html").html(myHtml);
})
这个问题的主要目的是了解这种行为的原因,并找到最佳解决方案。
问题是,当您使用jQuery的html(val)
时,它会执行以下操作:
html: function(value) {
/* ... */
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) && /* ... */) {
/* ... */ elem.innerHTML = value; /* ... */
}
/* ... */
}
也就是说,它使用正则表达式rnoInnerhtml
检查字符串,即
rnoInnerhtml = /<(?:script|style|link)/i
因此,大概是为了避免插入样式表,jQuery避免了innerHTML
,而使用domManip
做了一些复杂的事情。
我建议使用本机innerHTML
:
$("html").prop('innerHTML', myHtml);
var myHtml = "<head><title>Title Here</title><link href='style.css' rel='stylesheet' type='text/css'/></head><body style='background-color: red'><div>Div!</div></body>"
$("html").prop('innerHTML', myHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is the old html!
或者搭配香草js:
document.documentElement.innerHTML = myHtml;
var myHtml = "<head><title>Title Here</title><link href='style.css' rel='stylesheet' type='text/css'/></head><body style='background-color: red'><div>Div!</div></body>"
document.documentElement.innerHTML = myHtml;
This is the old html!
问题是在根html
元素中附加了一个html
元素,这是未定义的行为,浏览器无法可靠地呈现。从myHtml
字符串中去掉打开和关闭<html>
和</html>
标签,它就工作了!
工作演示
$(function() {
var myHtml = "<head><title>Title Here</title></head><body style='background-color: red; '><div>Div!</div></body>"
$('html').html(myHtml);
})
或者,您可以保留标记并直接写入document
对象,这将打开一个新的流并覆盖以前的文档。
// ...
document.write(myHtml);
相关文章:
- 如何设置html元素填充的动画
- 使用val()在jquery循环中设置html字符串的val
- 在 PHP 块中使用 Javascript 设置 HTML 文本框的值(使用 echo)
- JS for循环来设置HTML对象参数
- 使用JavaScript在select字段中使用optgroup设置html选项值
- 使用jQuery在select选项上设置HTML数据属性
- 设置html时的验证
- 如何从javascript中设置html表单的属性
- 如何使用Angular 2设置HTML选择值
- 设置 HTML 自定义属性与在 ID 属性中存储信息
- 无法通过javascript函数的自动计算设置html元素值
- 通过单选按钮状态设置HTML元素的可见性
- 通过参数设置html组合框的选定选项
- 使用javascript设置html页面的标题
- 如何从javascript设置html单选值
- 通过单独的js文件设置HTML值
- 我们如何使用Jquery和ASP.NET MVC 4复杂模型数据设置HTML元素的值
- 如何使用来自@Html.TextBoxFor的用户输入设置@Html.RadioButtonFor的值
- ckEditor插件iframe对话框设置html输入
- 如何从json中设置HTML选择选项