【发布时间】:2017-03-31 13:14:12
【问题描述】:
我有以下节点服务器和 index.html 文件,当我在浏览器的多个选项卡或窗口中打开 index.html 文件时,当我单击按钮时,它显示在所有打开的选项卡和窗口中单击的按钮,但按钮颜色不会在所有选项卡中更改,它只会在单击按钮的选项卡中更改。
app.js
const io = require('socket.io')(3000);
io.on('connection', function (socket) {
console.log('a client has connected');
socket.on('clicked', function() {
io.emit('clicked');
});
});
console.log('socket.io server started at port 3000');
index.html
<!doctype html>
<html>
<head>
<title>Testing socket.io</title>
</head>
<body>
<input type="button" id="button" style="width: 100px; padding: 10px; box-shaddow: 10px 6px 5px; #999999; -webkit-box-shadow: 6px 6px 5px #999999; -moz-box-shadow: 6px 6px 5px #999999; font-weight: bold; background: #16ed07; color: #000000; cursor: pointer; border-radius: 10px; border: 1px solid #D9D9D9; font-size: 150%;" value="Send!" onClick="onClickHandler(this)"/>
<h2 id="alert"> waiting...</h2>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script>
var socket = io("http://localhost:3000");
socket.on('connect', function() {
document.getElementById("button").addEventListener("click", function () {
socket.emit("clicked");
});
});
socket.on('clicked', function() {
console.log('clicked');
document.getElementById("alert").innerHTML = "send clicked";
});
</script>
<script type="text/javascript">
function onClickHandler(elem) {
elem.style.background = 'red';
elem.style.color = 'black';
}
</script>
</body>
</html>
【问题讨论】:
-
io.sockets.emit('clicked');
标签: javascript button socket.io onclick click