Javascript函数未在jquery onready之外定义

时间:2014-09-24 14:50:03

标签: javascript jquery

下面是我的js文件和两个div,我不明白为什么html2没有工作,我得到" sendMessage未定义"。有人可以向我解释......或者只是解释的链接。

由于

    $(function() {

        var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket

        var wsUrl = jsRoutes.controllers.P2.connect().absoluteURL();
        wsUrl = wsUrl.replace("http", "ws");

        var p2Socket = new WS(wsUrl)

        var sendMessage = function() {
            p2Socket.send(JSON.stringify(
                {text: "HI"}
            ))

        }   

            $("#buttonHi" ).click(function() {
             sendMessage()
             });
    });

function sendMessageOutside(){
         sendMessage();
}

和Html 1 ......

<div id="p2-console" style="border: 1px solid;">
    <button id="buttonHi" >Interact</button>
</div>

和Html 2 ......

<div id="p2-console" style="border: 1px solid;">
    <button id="buttonHi" onclick="sendMessageOutside()">Interact</button>
</div>

1 个答案:

答案 0 :(得分:2)

您正在jquery函数中本地定义sendmessage,sendMessageOutside()函数无法在该范围之外看到它。您需要将sendmessage定义为全局变量然后尝试它。

    var sendmessage;
     $(function() {

        var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket

        var wsUrl = jsRoutes.controllers.P2.connect().absoluteURL();
        wsUrl = wsUrl.replace("http", "ws");

        var p2Socket = new WS(wsUrl)

            sendMessage = function() {
            p2Socket.send(JSON.stringify(
                {text: "HI"}
            ))

        }   

            $("#buttonHi" ).click(function() {
             sendMessage()
             });
    });

function sendMessageOutside(){
         sendMessage();
}