javascript - 打开预先存在的页面并更改其中的一部分

标签 javascript jquery html

我正在使用 javascript 在新窗口/选项卡中打开 species_county 文件,然后使用 jquery 更改 ID 为 speciesTitle 的 h1 标签的内容。

open_event_test.html

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"    src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<body>

<p>Click the button to open a new window called "MsgWindow" with some text.    </p>

<button onclick="myFunction('Yada')">Yada</button>

<script>
function myFunction(species) 
{
      console.log(species);
      var myWindow = window.open("species_county.html", species);
      myWindow.document.getElementById("speciesTitle").html(species);
}
</script>

</body>
</html>

species_county.html

<!doctype html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<body>
<h1 id="speciesTitle">Species in County</h1>
</body>
</html>

我收到错误消息说我正在抓取的元素的值为 null。我只需要替换一些内容。 Document.write 不起作用,因为它不会打开 species_county 文件,它会创建一个全新的页面。

最佳答案

您的脚本可能存在一些问题。

1) 元素没有 html 方法

beercohol 所述,HTML Element 上没有 html() 这样的方法. html() 是一个 jQuery 方法,它是 jQuery 对象的一个​​属性。为了使用它,您需要使用 jQuery 来选择元素,或者使用 JavaScript 的原生 innerHTML 属性。

myWindow.document.getElementById("speciesTitle").innerHTML = species;

// or

$(myWindow.document).find('#speciesTitle').html(species);

2) 窗口/框架的 DOM 尚未加载

很有可能,当您运行更改 speciesTitle 元素的代码时,您打开的窗口尚未完成加载其 DOM。这将导致以下错误:

TypeError: myWindow.document.getElementById(...) is null

您需要以某种方式确保在新窗口的 DOM 完成加载之前不运行更改 HTML 的代码。传统上,这是 jQuery 的工作,但这是 myFunction 方法中的一个快速(非跨浏览器友好的)纯 JavaScript 示例:

function myFunction (species) {
  var myWindow = window.open("species_county.html", species);
  myWindow.onload = function() {
    // DOM has loaded
    this.document.getElementById("speciesTitle").innerHTML = species;
  }
}

3) 同源策略

出于安全原因,大多数浏览器不允许您调整另一个框架的窗口,除非两个框架来自同一来源。如果您在本地工作,很可能您没有使用匹配的域名或 IP 地址。 Chrome 不允许您通过文件系统进行这些通信(无论如何默认情况下都不是),但我在 Firefox 上取得了一些成功,在文件系统上本地文件之间放弃了同源策略。无论哪种方式,如果您尝试与来自完全不同域的框架进行通信,这都不会在合法浏览器上运行。

有关详细信息,请参阅 window.open() FAQ在 MDN 网站上。注意关于跨域的部分:

A script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name).

4) 弹出窗口拦截器

您也可能会遇到弹出窗口阻止程序的各种浏览器实现的问题。这些将完全拒绝打开新框架,导致 null 窗口对象。您首先需要通过浏览器中的某些配置“允许”您的页面打开一个窗口(通常弹出窗口拦截器图标会使其显而易见)。

关于javascript - 打开预先存在的页面并更改其中的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324300/

相关文章:

javascript - 如何在 IE8 中生成具有特定键码的 keyup 事件?

javascript - 如何删除获取 id 的一部分

html - 无法将 css 转换添加到背景图像

javascript - 如何使用 JavaScript 获取与元素 SPAN 样式相关的所有文本?

html - 如何通过单击图像切换侧边栏?

javascript - 如何使用 JavaScript 使标题标签内的文本具有动画效果?

C# 中来自 SQL Server 的 JavaScript 数组数据

javascript - typescript JSDoc ...休息类型语法

javascript - FuelUX - 向上打开日期选择器日历

javascript - Div 在复选框上切换,但在 div 外部时检测到单击以关闭