无法使用nodejs和jquery

时间:2016-12-28 16:18:13

标签: javascript jquery node.js

当我在端口3000上加载index.html并单击播放按钮时,所有消息都正确发送,但('#pause').click()未执行,因为音频没有暂停。

index.html代码:

<html>

<head>
  <script type="text/javascript" src="new.js"></script>
  <script src="/socket.io/socket.io.js"></script>
  <script src="jquery-3.1.1.min.js"></script>
</head>

<body>
  <button type="button" id="play" name="play" value="play">PLAY</button>
  <button onclick="pauseAd()" type="button" name="pause" value="pause">PAUSE</button>
  </br>
  <audio controls id="song">
    <source src="Lyrics to Swallowed in the Sea - Coldplay.mp3" type="audio/mpeg">
  </audio>

  <div id="messages"></div>

  <script>
    var socket = io.connect("http://localhost:3000");

    $(function() {
      $('#play').bind('click', function() {
        alert("User clicked on play");
        playAd();
        socket.emit('msg', {
          sent: 1
        });
        return false;
      });
    });


    socket.on('msg-received', function(data) {
      if (data.value == 1) {
        $('#pause').click();
        $('#messages').append('<p>message received' + data.value + '</p>')
      }
    });
  </script>
</body>

</html>

服务器代码:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static('./Public'));


app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.get("/", function(req, res) {
  res.render("new");
});


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

  console.log("user connected");
  socket.on('msg', function(data) {
    console.log("message received", data);

    socket.emit('msg-received', {
      value: 1
    });
  });
});

http.listen(3000, function() {
  console.log('listening on *:3000');
});

1 个答案:

答案 0 :(得分:1)

$('#pause')是jQuery的id选项,用于id属性为pause的元素。您目前没有id属性为pause的元素,因此$('#pause')目前不返回任何内容。

要解决您的问题,您只需将属性id='pause'添加到暂停按钮即可:

<button id='pause' onclick="pauseAd()" type="button" name="pause" value="pause">PAUSE</button>

当您选择ID为pause

的元素时,这将使JQuery选择按钮

希望这有所帮助,如果您需要进一步澄清,请告诉我。