`document` is not defined Electron
我正在尝试使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | dialog.showOpenDialog((filenames) => { if (!filenames) return; fs.readFile(filenames[0], (err, data) => { if (err) { alert('Could not read file.\ \ Details:\ ' + err.message); return; } let json = JSON.parse(data).en; for (let i = 0; i < json.length; ++i) { let html =""; // Add more to html variable from json data $('list').html(html); } }); }); |
我收到一条错误消息:
Uncaught Exception:
Error: jQuery requires a window with a document
如何从JS修改DOM,为什么会出现此错误?
您可以使用BrowserWindow的webContents的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | const { app, BrowserWindow} = require('electron') const path = require('path') const fs = require('fs') app.once('ready', () => { var mainWindow = new BrowserWindow() mainWindow.loadURL(path.join(__dirname, 'index.html')) fs.readFile(path.join(__dirname, 'test.json'), 'utf8', (err, data) => { if (err) { alert('Could not read file.\ \ Details:\ ' + err.message) return } let json = JSON.parse(data) for (let i in json) { mainWindow.webContents.executeJavaScript(` document.getElementById("list").innerHTML += ' ${i}: ${json[i]}' `) // can be replaced with // $('#list').append(' ${i}: ${json[i]}') // if html have jquery support } }) }) |
为了在电子中使用jquery,您应该安装
1 | window.$ = window.jQuery = require('jquery'); |
详细说明可在此处找到
你可以试试这个
1 | window.$ = require('jquery')(window); |
它为我纠正了这个错误