在本教程中,https://www.w3schools.com/nodejs/nodejs_raspberrypi_webserver_websocket.asp,它甚至有处理程序,工作了一个HTML复选框.我想做完全相同的事情,但有一个按钮,这样我就可以暂时打开一扇门。只要鼠标按下按钮,门就会解锁。释放鼠标按钮后,门锁上。默认位置为锁定。下面是上面链接的代码:
<!DOCTYPE html>
<html>
<body>
<h1>Control LED light</h1>
<p><input type="checkbox" id="light"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script> <!-- include socket.io client side script -->
<script>
var socket = io(); //load socket.io-client and connect to the host that serves the page
window.addEventListener("load", function(){ //when page loads
var lightbox = document.getElementById("light");
lightbox.addEventListener("change", function() { //add event listener for when checkbox changes
socket.emit("light", Number(this.checked)); //send button status to server (as 1 or 0)
});
});
socket.on('light', function (data) { //get button status from client
document.getElementById("light").checked = data; //change checkbox according to push button on Raspberry Pi
socket.emit("light", data); //send push button status to back to server
});
</script>
</body>
</html>
本质上,我想用
<input type="button" id="light" value="light">
而不是
<input type="checkbox" id="light">
谢谢你!
2条答案
按热度按时间o4tp2gmn1#
在按钮上使用数据属性
ibrsph3r2#
为了让代码完全按照我想要的方式工作,我做了以下事情:
我添加了以下JavaScript:
@mplungjan再次感谢!