Web 工作者未使用 onclick

Web worker not working with onclick

本文关键字:onclick 未使用 工作者 Web      更新时间:2023-09-26

我试图弄清楚 Web Workers 的行为,我有点困惑为什么输出仅在函数分配给 window.onload 事件时显示并保留消息,以及为什么在函数末尾添加 alert() 会在单击"确定"之前暂时显示消息并且消息消失。

感谢任何帮助,谢谢。

<form>
    <button id="button" style="height:30px;">Say hello</button>
    <input id="output" style="width:200px"></input>
 </form>
 <script>
    var button = document.getElementById("button");
    button.onclick = function(){
      var worker = new Worker("worker.js");
      worker.postMessage("hello");
      worker.onmessage = function(event){
        var message = event.data;
        var output = document.getElementById("output");
        output.value = "Worker says " + message;
      }
      //alert("Message shows when this alert is here, but as "
      //       + "soon as you click ok...");
    }  
 </script>

工人.js

onmessage = function(){
  postMessage("Well hello to you too.");
}

您的工作人员在您设置打开消息回调之前发送回复。因此,当您这样做worker.onmessage = ...时,"Hello to you too"消息已经消失了。

始终首先分配回调,这也适用于 XHR 请求和图像的onload回调。这样做:

  var worker = new Worker("worker.js");  
  worker.onmessage = function(event){
    var message = event.data;
    var output = document.getElementById("output");
    output.value += "Worker says " + message + "'n";
  }
  worker.postMessage("hello");

我也不确定为什么你使用表单,当它是一个javascript程序并且你不想向服务器发送任何东西时......只需使用<div>

<div>
    <button id="button" style="height:30px;">Say hello</button>
    <input id="output" style="width:200px"></input>
</div>

如果您有<button> <form>它会发送表单并在您单击页面时重新加载页面 - 除非它是<button type="button">