jQuery如果还没有处理点击

时间:2012-12-30 11:02:29

标签: jquery node.js

我一直试图让这个工作,但没有成功。代码似乎在第一次单击时正常工作,但是在几次单击后,它会随机输出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 ifition之后点击,但结果相同。

<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>

1 个答案:

答案 0 :(得分: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"});
                     }
            }); 

我希望这会对你有所帮助。