javascript - 使用 jquery/javascript 从卸载的文档中加载 html 头

标签 javascript jquery html get head

我正在为我父亲的驾驶学校重写一个网站,将不必要的 iframe 和图像更改为 html5 和 css3 标记,并通过 javascript 和 jquery 改进功能。

现在,我为每个菜单项(对于搜索爬虫)都有一个完整的页面,而标题和菜单大部分保持不变。这就是为什么我想使用历史 API 并在启用了 JavaScript 的设备上单击链接时更改内容以及文档标题和描述,这样就不必刷新整个页面。

什么有效: - 获取目标页面的#content div并加载到当前页面 - 使用history api显示新的url并使用popstate事件返回之前的状态 - 更改当前文档的 html 头部内容

什么不起作用: - 从目标文档获取html头

应该有一个简单的函数来实现这个,对吧?或者有什么好的方法吗?

最佳答案

由于它们具有相同的起源,因此您可以做到这一点。这有点尴尬,尽管它与 jQuery 在使用 ajax 时在幕后所做的事情相差不到一百万英里 load (我希望 jQuery 使用文档片段而不是 iframe )。

基本上,您可以创建一个页外 iframe ,将内容页面加载到那里,然后从中提取您需要的任何内容,如下所示(完全未优化):

// I'm assuming you have a variable containing the content URL; I'll use `page`
var page = "/ocazuc/2";

// Create the iframe, put it off-page, and put it in the DOM
var iframe = $('<iframe>');
iframe.css({
  position: "absolute",
  left: -10000
}).appendTo(document.body);

// Hook the load event on it
iframe.load(function() {
  // Get the document
  var $doc = $(iframe[0].contentDocument.documentElement);

  // Steal its content
  $doc.find("body").contents().appendTo(document.body);

  // And use its title or whatever else you want from the `head`
  document.title = $doc.find('title').text();

  // Done with it
  iframe.remove();
});

// Start loading it
iframe[0].src = page;

Live Example | Source

关于javascript - 使用 jquery/javascript 从卸载的文档中加载 html 头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15364493/

相关文章:

javascript - 为什么 JavaScript 解释器得到 -8 作为语句 parseInt(1/8-9,23) 的结果?

javascript - 通过 ajax 将变量从我的表单获取到我的解析器文件

jquery - Bootstrap 可折叠导航,屏幕宽度为 1280 像素

javascript - 由 <canvas/> 内存在页面重新加载时免费分配

javascript - 正则表达式——不带尾随字符的匹配

javascript - jsonschema-master 验证 json 请求未按预期响应

javascript - 如何从两个单独的 HTML id 中复制一个值?

javascript - 提交时仅在 jQuery 中显示一次消息

javascript - Ext JS 中方向改变时的对话框位置改变

javascript - React Component Array Map - 渲染没有返回任何内容。这通常意味着缺少返回语句。或者,不渲染任何内容,返回 null