简体   繁体   English

通过Socket.io控制HTML页面

[英]Controlling a HTML page via Socket.io

I´d like to control the look of a HTML page using the strings I receive from my Node.js server via Socket.io. 我想使用通过Socket.io从Node.js服务器收到的字符串来控制HTML页面的外观。 Each string I receive becomes an entry in a list (see screenshot below). 我收到的每个字符串都将成为列表中的一个条目(请参见下面的屏幕截图)。 Until here it works. 直到这里工作。 Now, I want to use these strings to control other things, for example the color of the heading 现在,我想使用这些字符串来控制其他事情,例如标题的颜色

I´m using a string comparison. 我正在使用字符串比较。 I tried to turn the heading green whenever the received string is "on". 每当接收到的字符串为“ on”时,我都尝试将标题变为绿色。 However, the following command does not turn the heading green: 但是,以下命令不会使标题变为绿色:

if(receivedData == "on") 
{
    $("#currentData").css("color", "green");
}

But if I tell my computer to turn the heading green when any message other than "on" comes in. Then the heading is turning green. 但是,如果当我收到除“开”以外的任何消息时,我告诉我的计算机将标题变为绿色。则标题变为绿色。 However the incoming message is exactly "on"! 但是,传入消息恰好是“打开”! In this case the heading should not become green! 在这种情况下,标题不应变为绿色!

if(receivedData != "on") 
{
    $("#currentData").css("color", "green");
}

What am I doing wrong? 我究竟做错了什么?

Here is the complete client-side HTML code and the link to a screenshot. 这是完整的客户端HTML代码和屏幕快照的链接。

<!doctype html>
<html>
    <head>
        <title>Browser Info Panel</title>
        <link rel="stylesheet" type="text/css" href="./styles.css">
    </head>

    <body>
        <div id="currentData"> <h1> CurrentData </h1> </div>
        <ul id="messages" /ul>


        <script src="/socket.io/socket.io.js"></script>
        <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
        <script>    
            var receivedData;
            var socket = io();
            socket.on('chat message', function(msg)
            {
                $('#messages').append($('<li>').text(msg));
                receivedData = msg;

                if(receivedData != "on") 
                {
                    $("#currentData").css("color", "green");
                }
            });
        </script>  
    </body>
</html>

Screenshot: http://i.imgur.com/ruZP0x5.jpg 截图: http//i.imgur.com/ruZP0x5.jpg

This seems like a problem with String comparison. 这似乎是字符串比较的问题。 Are you sure that there is no whitespace or some weird unicode characters in receivedData ? 你肯定没有空格或一些怪异的Unicode字符receivedData Try it again with .trim() . 使用.trim()再试一次。

Check these: 检查这些:

https://stackoverflow.com/a/19649034/1528880 https://stackoverflow.com/a/19649034/1528880

https://stackoverflow.com/a/1706650/1528880 https://stackoverflow.com/a/1706650/1528880

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM