-3

これら 3 つの関数が互いにどのように関連しているかを誰か説明できますか?ここで $ が行っている関数は何ですか? それには2つの定義がありますか?

socket.onopen = function(){
    log("Welcome - status "+this.readyState); 
};

function $(id){ 
   return document.getElementById(id); 
}

function log(msg){ 
    $("log").innerHTML+="<br>"+msg; 
}

これらの関数は、以下のクライアント コードで記述されます。

var ソケット;

function init() {
    var host = "ws://localhost:12345/websocket/server.php";
    try {
        socket = new WebSocket(host);
        log('WebSocket - status ' + socket.readyState);
        socket.onopen = function (msg) {
            log("Welcome - status " + this.readyState);
        };
        socket.onmessage = function (msg) {
            log("Received: " + msg.data);
        };
        socket.onclose = function (msg) {
            log("Disconnected - status " + this.readyState);
        };
    } catch (ex) {
        log(ex);
    }
    $("msg").focus();
}

function send() {
    var txt, msg;
    txt = $("msg");
    msg = txt.value;
    if (!msg) {
        alert("Message can not be empty");
        return;
    }
    txt.value = "";
    txt.focus();
    try {
        socket.send(msg);
        log('Sent: ' + msg);
    } catch (ex) {
        log(ex);
    }
}

function quit() {
    log("Goodbye!");
    socket.close();
    socket = null;
} // Utilities  function $(id){ return document.getElementById(id); }  function log(msg){ $("log").innerHTML+="<br>"+msg; }  function onkey(event){ if(event.keyCode==13){ send(); } }
4

4 に答える 4

4

最初の関数は 3 番目の関数を呼び出します。3 番目の関数は 2 番目の関数を呼び出します。それらの間に他の関係はありません。

$変数名では、この文字に特別な意味はありません。fooまたはgetEl代わりに使用できます。

$は、(a) 短く、(b) 変数の開始を示すために他の言語で使用される文字であるため、要素を取得する関数で一般的になった特に有益でない名前です。

于 2013-02-27T06:53:04.057 に答える
2

id $-string を受け取り、

documet.getEelementById(id);

単純。

于 2013-02-27T06:52:53.463 に答える
1

最初の関数はイベント ハンドラーです。socketオブジェクトがイベントを発生させるたびにopen、JavaScript は で定義された関数を呼び出しますsocket.onopenlogこの関数は、以下に定義されている名前の別の関数を呼び出します。

2 番目の関数は、 の短縮形を作成しdocument.getElementById()ます。$文字は JavaScript の通常の識別子として使用できるため、一般的な関数を短縮するための便利なツールになります。ここでの注意点は、いくつかの一般的な js ライブラリがそのシンボルを主要な機能に使用することです。そのため、カスタム コードではおそらくこれを避ける必要があります。

このlog関数は省略形を使用して要素を選択し、連結によってメッセージのテキストを受け取ります。既に存在するテキストには、メッセージ テキストが追加されます。

于 2013-02-27T07:03:36.070 に答える
0

書き換え:

// Binds an anonymous function to the open event of the 
// object named socket. The handler function prints a
// status message in the log panel by invoking the 
// function defined below named log.

socket.onopen = function () {
    log("Welcome - status " + this.readyState); 
};

// Function named $ that returns the DOM element
// whose id attribute equals id.

function $(id) { 
    return document.getElementById(id); 
}

// Function named log that invokes the function named $.
//
// This function finds the DOM element whose id equals
// "log" and appends a line break and a message to its
// inner content.

function log(msg) { 
    $("log").innerHTML += "<br>" + msg; 
}
于 2013-02-27T06:58:43.003 に答える