在有关Electron.js的this tutorial中,用户的动作处理已直接在html文件中实现(您无需分析下面的代码,我只想显示这个概念):
<!doctype html>
<html lang="en">
<head>
<title>Shopping list</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
</head>
<body>
<nav>
<div class="nav-wrapper">
<a class="brand-logo center">Shopping list</a>
</div>
</nav>
<ul></ul>
<script>
const Electron = require('electron');
const { ipcRenderer } = Electron;
const ul = document.querySelector('ul');
ipcRenderer.on('item:add', (event, item) => {
ul.className = 'collection';
const li = document.createElement('li');
li.className = 'collection-item';
const itemText = document.createTextNode(item);
li.appendChild(itemText);
ul.appendChild(li);
});
ipcRenderer.on('item:clear', () => {
ul.innerHTML = '';
if (ul.children.length === 0) {
ul.className = '';
}
});
ul.addEventListener('dblclick', removeItem);
function removeItem(event) {
event.target.remove();
if (ul.children.length === 0) {
ul.className = '';
}
}
</script>
</body>
</html>
我想,这种方法很适合用于教程,但是通常,HTML文件中的逻辑在实际应用程序中是不可接受的。如何将脚本与html文件关联并访问HTML元素?