首先我要说我已经通过从根本上改变我的方法解决了这个问题。但在解决它的过程中,我整理了一个让我着迷和烦恼的测试用例。
我有一个从 AJAX 调用返回的字符串。该字符串包含 HTML,其中大部分无用。我想将字符串(及其所有子元素)中的一个元素插入到 DOM 中。对此的模拟是:
<!DOCTYPE html>
<html>
<head>
<title>wtf?</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
var markup = '<div class="junk"><div class="good"><time datetime="2013-03-29">March 29, 2013</time></div></div>',
output = $(markup).find('.good').clone().wrap('<div />').parent().html();
$('body').append(output);
});
</script>
</head>
<body></body>
</html>
我在此处有此文件的托管副本:http://alala.smitelli.com/temp/wtf_ie.html (不会永远出现)。
这应该做的是提取 .good
div 和 child <time>
元素,然后将它们插入正文。我做.wrap().parent()
提取我选择的元素及其子元素(参见 this question )。 .clone()
和 .html()
是证明问题的发明。
对于用户来说,它应该显示今天的日期。它适用于 Chrome、Firefox、IE9 等:
March 29, 2013
但是在IE7和8中,显示的文字是:
<:time datetime="2013-03-29">March 29, 2013
开幕<
被显示,并且以某种方式插入了一个冒号。闭幕</time>
标记看起来不受影响,并且未显示为已转义。
这是怎么回事?这是某种错误,还是预期的行为?结肠从哪里来?
编辑:至于添加 document.createElement('time')
的建议或 html5shiv,这些似乎都没有改变行为。
最佳答案
非常 令我惊讶的是,我发现如果我在实际解析标记方面从等式中删除 jQuery,问题就会消失(在 IE7 和 IE8 上),即使没有 createElement('time')
或 shim/shiv:
<!DOCTYPE html>
<html>
<head>
<title>wtf?</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
var div, markup, output;
markup = '<div class="junk"><div class="good"><time datetime="2013-03-29">March 29, 2013</time></div></div>';
div = document.createElement('div');
div.innerHTML = markup;
output = $(div).find('.good').clone().wrap('<div />').parent().html();
$('body').append(output);
});
</script>
</head>
<body></body>
</html>
这里的变化是我只是使用浏览器自己处理 innerHTML
和一个断开连接的 div
来解析 markup
,而不是让 jQuery为我做。
所以我不得不说这可能是 jQuery 在不支持 HTML5 元素的旧浏览器上处理 HTML 片段的问题。但这将是一个重要的主张,而重要的主张需要重要的证据......
但是如果我改变这些行:
div = document.createElement('div');
div.innerHTML = markup;
output = $(div).find('.good').clone().wrap('<div />').parent().html();
到:
div = $(markup);
output = div.find('.good').clone().wrap('<div />').parent().html();
我遇到了问题(在 IE7 和 IE8 上):Live Copy | Source
所以它确实开始看起来像一个 jQuery 问题......
关于javascript - IE7/8 + <time> 标签 + jQuery .clone() =?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15708937/