如何通过单击按钮触发JavaScript

时间:2019-03-30 17:16:59

标签: javascript html css node.js

我正在尝试触发javascript以从html文件中的按钮启动,停止和重新启动秒表。将事件从html传递到javascript的最佳方法是什么?

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

server.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!');
});

client.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中运行

3 个答案:

答案 0 :(得分:1)

在client.js中使用

window.addEventListener("load", myFunction);

并将您的代码放置到myFunction

答案 1 :(得分:1)

如果已打印此控制台,请console.log('正在运行客户端代码');

尝试将按钮事件添加到函数中。

function onLoadBody() {
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
  console.log('button was clicked');
});
}
<body onload="onLoadBody()" >...

答案 2 :(得分:0)

假设您有两个文件,client.js和server.js 您可以使用socket.io更快地响应HTTP请求 您只需要向服务器发出密钥,服务器就会响应该密钥。 Client.js

let socket = io();
socket.emit('start')

Server.js

socket.on('start',(data)=>{
// do what ever you want and send back to client with the same emit method 
// `socket.emit()` sends message to connected client
// socket.broadcast.emit() send message to all clients except you
// io.emit() send message to all including you
})