如何使用HTML按钮满足JavaScript门解锁要求?

hrirmatl  于 2023-05-16  发布在  Java
关注(0)|答案(2)|浏览(138)

在本教程中,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">

谢谢你!

o4tp2gmn

o4tp2gmn1#

在按钮上使用数据属性

<input type="button" id="light" value="light" data-checked="0">
window.addEventListener("load", function(){ //when page loads
  const lightButton = document.getElementById("light");
  lightButton.addEventListener("mousedown", function() { //add event listener for when checkbox changes
    socket.emit("light", Number(this.dataset.checked)); //send button status to server (as 1 or 0)
  });
});
socket.on('light', function (data) { //get button status from client
  lightButton.dataset.checked = data; //change checkbox according to push button on Raspberry Pi
  socket.emit("light", data); //send push button status to back to server
});
ibrsph3r

ibrsph3r2#

为了让代码完全按照我想要的方式工作,我做了以下事情:

<input type="button" id="light" value="light" data-checked="1" data-unchecked="0">

我添加了以下JavaScript:

var socket = io();
window.addEventListener("load", function(){ //when page loads
const lightButton = document.getElementById("light");
lightButton.addEventListener("mousedown", function() { //add event listener for when checkbox changes
socket.emit("light", Number(this.dataset.checked)); //send button status to server (as 1 or 0)
});
const lightButton = document.getElementById("light");
lightButton.addEventListener("mouseup", function() { //add event listener for when checkbox changes
socket.emit("light", Number(this.dataset.unchecked)); //send button status to server (as 1 or 0)
});
});
socket.on('light', function (data) { //get button status from client
lightButton.dataset.checked = data; //change checkbox according to push button on Raspberry Pi
socket.emit("light", data); //send push button status to back to server
});

@mplungjan再次感谢!

相关问题