簡體   English   中英

Newby:index.js 文件在 index.html 文件中不起作用

[英]Newby: index.js file doesn't work in index.html file

我是 Javascript 世界的新手,目前我正在嘗試使用電子 js 框架實現 GUI。 嘗試從教程中重現代碼時,我遇到了一個似乎無法在我的 PC 上運行的代碼,基本上即使我單擊一個按鈕,控制台也沒有記錄任何內容(應該有的時候!!); 代碼的目的是從包含腳本的index.js中引用index.html文件中定義的按鈕,並在單擊按鈕時記錄一個句子,但似乎 html 文件中的腳本無法訪問 . js 文件。 我在這里報告index.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">
<title>my-app</title>
<link rel = "stylesheet" href="styles.css">
</head>
<body>
<button id = "button1" > START </button>
<script>
    require('./index.js'); 
</script>
</body>
</html>

這里屬於index.js文件的代碼:

const electron = require("electron");
const button1 = document.getElementById("button1");

button1.addEventListener("click", startApp);

function startApp(){
    console.log("Button clicked!");
  
};

注意:我嘗試根據我對 Javascript 和電子的很少知識來調試此代碼:

  1. 我使用了document.getElementById("button1"); index.html確實有效(獲得的變量用於更改按鈕文本顏色),但在index.js文件中報告時同樣無效
  2. 我試過console.log("In index.js"); index.js但仍然無法正常工作

從這些結果我認為問題可能是 .html 和 .js 文件通信; 它們在同一個文件夾中。 還有一件事:我從 GitHub 下載了教程代碼,但問題仍然存在,第 1 點和第 2 點的操作相同。

編輯:我省略了我正在鏈接index.html窗口並將其顯示在main.js文件中,實際上窗口確實顯示了,但是單擊按鈕不會產生任何操作。

一旦准備就緒,您似乎應該使用電子通過BrowserWindow加載 index.html 。 appBrowserWindow來自電子模塊。

`const { app, BrowserWindow } = require('electron')`

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600
  })

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()
})

從快速開始

  • 在 Electron 中,瀏覽器窗口只能在 app 模塊的 ready 事件被觸發后創建。 您可以使用 app.whenReady() API 等待此事件。 在 whenReady() 解析其 Promise 之后調用 createWindow()。

有關更多信息,請參閱https://www.electronjs.org/docs/tutorial/quick-start

希望這證明是有用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM