0

我有一个html页面:

<html>
<head>
<script type="text/javascript">
function myfunct()
{
window.location='test.html';
document.getElementById("message")="hello";
}
</script>
</head>
<body>
<input type="button" value="click" onclick="myfunct()"/>
</body>
</html>

测试.html:

<html><head></head>
<body>
<div id="message">Some text</div>
</body>
</html>

问题是window.location工作正常,但 div 没有更新为“hello”。

4

4 回答 4

2

您不能将字符串分配给元素,您必须使用该innerHTML属性。此外,由于元素位于您打开的页面中,因此您必须在该页面中拥有代码。

测试.html:

<html>
<head>
<script type="text/javascript">

window.onload = function() {
  document.getElementById("message").innerHTML = "hello";
}

</script>

</head>
<body>
<div id="message">Some text</div>
</body>
</html>

如果要从第一页发送消息,则必须将其作为数据发送到新页面,以便它可以显示它:

在第一页:

window.location.href = 'test.html?hello';

在 test.html 中:

window.onload = function() {
  document.getElementById("message").innerHTML = window.location.search.substr(1);
}
于 2011-04-11T05:50:36.827 回答
1

您尝试设置为“Hello World”的元素在您正在使用的页面上不存在。您只能访问当前页面上的元素。当页面刷新发生时,它会从请求的页面重新创建 HTML DOM。您不能直接访问其他页面 DOM。

于 2011-04-11T05:44:21.840 回答
1

你必须写在 test.htm

document.getElementById("message")="hello";

不在你的html中

于 2011-04-11T05:50:26.423 回答
1

你必须写

函数 myfunct() { document.getElementById("message")="hello"; }

在 test.html 页面中...

并在 test.html 的页面加载事件上调用此函数

于 2011-04-11T05:46:54.473 回答