2

我一直试图让这个工作,但没有成功。该代码似乎在第一次单击时可以正常工作,但在几次单击后,它会随机输出两个 if 条件的次数。

在服务器端,我在 Node.js 上

var sys = require('sys');
var net = require('net');
var mqtt = require('mqttclient');

var io  = require('socket.io').listen(5000);
var client = new mqtt.MQTTClient(1883, '192.168.1.33', 'SERVER NODO');

io.sockets.on('connection', function (socket) {
  socket.on('subscribe', function (data) {
    console.log('Subscribing to '+data.topic);
    client.subscribe(data.topic);
  });

});


io.sockets.on('connection', function (socket) {

socket.on('publish', function (data){
console.log('publishing to '+data.topic);
client.publish(data.topic,data.payload);

});


});

//Sends to Web 
client.addListener('mqttData', function(topic, payload){
  sys.puts(topic+'='+payload);
  io.sockets.emit('mqtt',{'topic':String(topic),
    'payload':String(payload)});
}); 

在客户端,我有这个页面,它可以正确加载,第一个 if 块似乎很好,是我遇到麻烦的第二个块。我没有任何编程经验,但我正在努力学习!

已经尝试了不同的组合以使其正常工作(例如,在 if contition 之后单击 on,但结果相同。

<link rel="stylesheet" href="style2.css">
<script type="text/javascript" src="http://192.168.1.33:5000/socket.io/socket.io.js</script>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
  var socket = io.connect('http://192.168.1.33:5000');
$(document).ready(function(){
    socket.on('connect', function () {
      socket.on('mqtt', function (msg) {

        console.log(msg.topic+' '+msg.payload);

           var classe = 0;

                if (msg.topic == "uno"){

                  if (msg.payload == "a")
                     $('#button').addClass('on');
                      classe = 1;       
                  if (msg.payload == "b")
                     $('#button').removeClass('on');
              casse = 0;        


            }

            $('#button').on('click', function(){

                        if (classe == 1)){ 
                               classe = 3;
                               socket.emit('publish',{topic:"unor", payload:"off"});
                        }

                        if (classe == 0){
                               classe = 3;
                               socket.emit('publish',{topic:"unor", payload:"on"});

                        }
            }); 

}); 

 socket.emit('subscribe',{topic:"uno"});


});
</script>
<tbody>
        <section>
            <a href="#" id="button">&#xF011;</a>
            <span></span>
        </section>
</tbody>
4

1 回答 1

1

您的问题可能是点击事件尝试使用以下代码。

$('#button').off('click').on('click', function(){

      if (classe == 1)){ 
               classe = 3;
               socket.emit('publish',{topic:"unor", payload:"off"});
                      }

      if (classe == 0){
              classe = 3;
              socket.emit('publish',{topic:"unor", payload:"on"});
                     }
            }); 

我希望这对你有帮助。

于 2012-12-30T11:33:45.907 回答