$.ajax成功回调中返回的HTML不允许我将其放入jQuery包装器中并对其应用标准的jQuery方法。这是为什么?例如,此警报为空:
dataType: "html",
success: function(myHTML) {
var $myHTML = $(myHTML);
alert( $myHTML.html() ); // returns null
}
我的意图是使用jQuery方法修改myHTML(这就是为什么我需要将其放入jQuery包装器中),然后将修改后的html(full,包括<head>
、脚本等)作为字符串返回。但是我尝试的jQuery方法都不能处理$(myHTML)。为什么?
代码的工作版本如下:http://jsfiddle.net/supertrue/Uw5dc/
var getHTML = function ( url ){
$.ajax({
url: url,
dataType: "html",
success: function( myHTML ) {
// view the returned HTML
alert('Successfully grabbed this HTML: nn' + myHTML);
// the opening <html> tag is missing (no idea why)
myHTML.replace('<head>', '<html><head>');
// put it in a jQuery wrapper
var $myHTML = $(myHTML);
// use jQuery to manipulate it
// $myHTML.find('script').remove(); // just an example
// then view the final html
alert('$myHTML.html(): nn' + $myHTML.html()); // doesn't work!
// that didn't work; try getting outerHTML
$myHTML = $('<div></div>').append(myHTML);
alert('$myHTML.html(): nn' + $myHTML.html()); // highly incomplete! missing scripts and <head>, <body> wrappers
}
});
}
在这里查看jQuery
方法的文档(向下滚动到jQuery(html[, ownerDocument])
的部分),它说:
当传入复杂的HTML时,一些浏览器可能不会生成完全复制所提供的HTML源代码的DOM。如前所述,我们使用浏览器的.ninnerHTML属性来解析传递的HTML,并将其插入到当前文档中。在这个过程中,一些浏览器过滤掉某些元素,例如<html>lt;title>,或者<头部>元素。因此,插入的元素可能不能代表传递的原始字符串。
考虑到这一点,您不太可能使用$(html)
生成整个页面(即包括<html>
和类似的标签),只有与它的工作方式兼容的部分(例如,您通常在<body>
中使用的标签可能工作正常)。