gpt4 book ai didi

javascript - 如何通过单击按钮触发 javascript

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:11 24 4
gpt4 key购买 nike

我试图通过 html 文件中的按钮触发 javascript 来启动、停止和重新启动秒表。将事件从 html 传递到 javascript 的最佳方式是什么?

我已经设法在按下按钮时触发控制台日志,但我无法将 javascript 放入第二个 js 文件中。我只是收到错误。 socket.io 会工作吗?我调查了事件发射器和监听器,但我认为这超出了我的技能水平。

服务器.js

var express = require('express');
var app = express();
var path = require('path');
var Stopwatch = require("node-stopwatch").Stopwatch;
const EventEmitter = require('events');

var stopwatch = Stopwatch.create();

app.use(express.static('public'));

// start the express web server listening on 8080
app.listen(8080, () => {
console.log('listening on 8080');
});

// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});

stopwatch.start();

/*
stopwatch output test
*/

console.log("ticks: " + stopwatch.elapsedTicks);
console.log("milliseconds: " + stopwatch.elapsedMilliseconds);
console.log("seconds: " + stopwatch.elapsed.seconds);
console.log("minutes: " + stopwatch.elapsed.minutes);
console.log("hours: " + stopwatch.elapsed.hours);

//stop it now
stopwatch.stop();

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});

客户端.js

console.log('Client-side code running');


const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
});

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stopwatch</title>
</head>
<body>
<h1>Stopwatch</h1>
<p id="counter">Loading button click data.</p>
<button id="myButton">Click me!</button>
</body>
<script src="client.js"></script>
</html>

我希望在单击按钮时触发 javascript,但我无法在 client.js 中运行它

最佳答案

在client.js中使用

window.addEventListener("load", myFunction);

并将您的代码放入myFunction

关于javascript - 如何通过单击按钮触发 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55433860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com