我希望用户能够打开该网站,并且会出现一个提示,要求用户告诉他们有关自己的信息以及他们输入的文本在新窗口中显示?
<html>
<head>
<script>
var text = prompt("Tell us something about yourself ");
function newWindow() {
var OpenWindow = window.open("", "slayyyter", "height=300 , width=300");
}
function showText() {
OpenWindow.document.write(text);
}
</script>
</head>
<body>
<button onclick="showText()">A</button>
</body>
</html>
答案 0 :(得分:1)
该代码中包含三个错误。打开Web控制台(通常按F12键)以查看其中的某些消息。
提示字符串
"Tell us something about
yourself"
其中有一个换行符,需要删除,
在OpenWindow
中声明的变量newWindow
不在showText
内部的代码范围内。如果要全局声明OpenWindow
,请在var
内的变量名之前删除newWindow
,以防止全局变量被局部声明所遮盖。
newWindow
必须被调用
这是一个返回窗口对象而不是将其保存在全局变量中的示例:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Test</title>
<head>
<script>
"use strict";
var text = prompt("Tell us something about yourself");
function newWindow() {
return window.open("", "slayyyter",
"height=300 , width=300");
}
function showText() {
var openWindow = newWindow();
newWindow().document.write(text);
newWindow.close();
}
</script>
</head>
<body>
<button onclick="showText()"> A </button>
</body>
</html>
注意
document.write
对于使用JavaScript学习练习很有用,但是在写入文档后调用document.close
来完成文档的定稿-它会在打开的窗口中停止窗口加载指示器。
有关“ HTML5文档类型声明”,“在HTML中声明字符集”和“何时在JavaScript中使用严格模式”的详细信息。
答案 1 :(得分:0)
您将要使用浏览器的工具和JavaScript控制台,单击该按钮会说未定义OpenWindow。这是因为范围。 OpenWindow仅在定义它的位置存在-函数newWindow中。要在其他函数中访问它,请在外部声明(在var text
下可以)。您可以将其保留为定义但空白,然后再分配。因此,在“文本”的声明下只需加上var OpenWindow;
。然后在newWindow内部,从OpenWindow前面删除“ var”。您可能还有其他问题,因为我尚未测试过代码,但这是主要问题。
提示:
答案 2 :(得分:0)
恐怕您想要实现的目标并非那么容易实现,因为无法直接告诉新浏览器窗口您在第一个窗口中写的内容。
但是您可以这样做。
使用此代码段并将其另存为test.html
<html>
<head>
<script type="text/javascript">
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('id') == null) {
var text = prompt("Tell us something about yourself");
localStorage.setItem('myText', text);
window.open("test.html?id=new", "slayyyter");
} else {
document.write("You have written: " + localStorage.getItem('myText'));
}
</script>
</head>
</html>
作为旁注- window.open()接受URL作为第一个参数。您不能简单地输入一些文本或传递包含文本的字符串-它必须是有效的资源,例如图像,html文件,php等...