javascript 在页面之间发送命令/值

vwkv1x7d  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(118)

我在一个有2页的网站上工作,1是接收器,2是远程basicly,你可以在第2页输入文本,一旦你点击提交page1开始播放文本speatch消息与文本inut从page2
index.html(又称:第1页)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="src/style.css">
  </head>
  <body>
    <h1 id="header"></h1>

    <script src="src/script.js"></script>
  </body>
</html>

control.html(又名:第2页)

<body>
<center>
<form>
<h1 style="color:green">Javatpoint</h1>
<h3> Confirm password Validation Example </h3>
<!-- Enter Password -->
<td> Enter Password </td>
<input type = "password" name = "pswd1"> <br><br>
<button type = "submit" onclick="matchPassword()">Submit</button>
<script>
var pw1 = document.getElementById("pswd1");
function matchPassword() {
  <script src="script.js"><script> var x1
}
</script>

第1页的脚本. js

const message = 'Hello world' // Try edit me

// Update header text
document.querySelector('#header').innerHTML = message

// Log to console
console.log(message)
var audio = new Audio('notif.mp3');
audio.play();
var msg = new SpeechSynthesisUtterance();
msg.text = "hallo jeremy";
window.speechSynthesis.speak(msg);

我找不到一种方法来发送这文本内page2到page1

de90aj5v

de90aj5v1#

有很多方法可以实现这一点,但我只展示一种方法:使用query parameters可以轻松地在页面之间传递数据,这些数据实际上是附加到URL末尾的数据片段。
为了利用这些功能,每当用户按下control.html页面中的按钮时,您需要重定向到index.html页面。幸运的是,这可以通过向Submit按钮添加事件侦听器来实现。
下面是代码:

    • 控件. html**
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <form>
      <p>Enter stuff here:</p>
      <input type="text" id="text-input" name="text" />
      <input type="submit" id="submit-button"></input>
    </form>
    <!-- continue document... -->
    <script src="src/control.js"></script>
  </body>
</html>
    • 源代码/脚本. js**
const queryString = window.location.search;
const queryParams = new URLSearchParams(queryString);

const message = queryParams.get("text");

console.log(message);

// continue file...
    • 源代码/控件. js**
const button = document.getElementById("submit-button");
button.addEventListener("click", handleText);

function handleText(event) {
  event.preventDefault();

  const text = document.getElementById("text-input").value;
  const currentURL = window.location.pathname;
  const currentDir = currentURL.substring(0, currentURL.lastIndexOf("/"));

  window.location.replace(currentDir + "/index.html?text=" + text);
}

希望这有帮助!

相关问题