我正在进行一个ajax调用来获取内容,并像这样追加这个内容:
$(function(){
var site = $('input').val();
$.get('file.php', { site:site }, function(data){
mas = $(data).find('a');
mas.map(function(elem, index) {
divs = $(this).html();
$('#result').append('' + divs + '');
})
}, 'html');
});
问题是,当我在body
中更改a
时,我什么也得不到(没有错误,没有html)。我假设body是一个标签,就像'a‘是?我做错了什么?
所以这对我来说很有效:
mas = $(data).find('a');
但这不是:
mas = $(data).find('body');
发布于 2013-01-20 18:00:53
我做了一些实验,并在一定程度上找出了原因,所以在等待我感兴趣的真正答案之前,这里有一个技巧来帮助理解这个问题。
$.get('/',function(d){
// replace the `HTML` tags with `NOTHTML` tags
// and the `BODY` tags with `NOTBODY` tags
d = d.replace(/(<\/?)html( .+?)?>/gi,'$1NOTHTML$2>',d)
d = d.replace(/(<\/?)body( .+?)?>/gi,'$1NOTBODY$2>',d)
// select the `notbody` tag and log for testing
console.log($(d).find('notbody').html())
})
编辑:进一步的实验
如果你把内容加载到一个iframe中,然后你可以通过某个dom对象层次结构来访问框架内容,这似乎是可能的……
// get a page using AJAX
$.get('/',function(d){
// create a temporary `iframe`, make it hidden, and attach to the DOM
var frame = $('<iframe id="frame" src="/" style="display: none;"></iframe>').appendTo('body')
// check that the frame has loaded content
$(frame).load(function(){
// grab the HTML from the body, using the raw DOM node (frame[0])
// and more specifically, it's `contentDocument` property
var html = $('body',frame[0].contentDocument).html()
// check the HTML
console.log(html)
// remove the temporary iframe
$("#frame").remove()
})
})
编辑:更多研究
似乎contentDocument是获取iFrame的window.document
元素的符合标准的方法,但IE当然并不真正关心标准,所以这就是如何以跨平台的方式获得对iFrame的window.document.body
对象的引用……
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
var iframeBody = iframeDoc.body;
// or for extra caution, to support even more obsolete browsers
// var iframeBody = iframeDoc.getElementsByTagName("body")[0]
发布于 2019-08-11 20:00:37
为我工作的Regex解决方案:
var head = res.match(/<head.*?>.*?<\/head.*?>/s);
var body = res.match(/<body.*?>.*?<\/body.*?>/s);
https://stackoverflow.com/questions/14423257
复制相似问题