带负载的奇怪JQuery行为

时间:2011-01-21 14:42:55

标签: jquery find

我坚持使用此代码。为什么这不能抓住身体元素?

$('#holder').load('Login.html', function(result) {
   alert(result); //shows complete body with <html> and <body>

   var body = $(result).children("body")[0]; //null
   var body = $(result).find("body")[0];     //null 
});

更新:

当我提醒时:alert($(result).children().length);它会显示3(<title>, <meta>, <div>

3 个答案:

答案 0 :(得分:0)

实际上我不确定你是否需要处理<body>。 jQuery会自动使用<body>标记内的内容。

$('#holder').load('Login.html', function() {
   alert($('#holder').html()); // contains just what you want
   // you can now do whatever you wanted to do here
   alert($("#holder div").text()); // text of all <div>s within Login.html
});

答案 1 :(得分:0)

根据文件http://api.jquery.com/load/

  

jQuery使用浏览器的.innerHTML属性来解析检索到的文档并将其插入到当前文档中。在此过程中,浏览器通常会过滤文档中的元素,例如<html><title><head>元素。因此,.load()检索的元素可能与浏览器直接检索文档的内容不完全相同。

答案 2 :(得分:-1)

因为我相信回来的是文本而不是dom元素,如果它是一个dom元素,$(result)会起作用,但它只是文本。最好的办法是只返回一个html片段,而不是整个文档。

相关问题