ReferenceError:函数未定义 - JavaScript [英] ReferenceError: function is not defined - JavaScript

查看:115
本文介绍了ReferenceError:函数未定义 - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在后端创建一个 Javascript 聊天,其中 Python 。这是我使用的代码...

 < html> 
< head>
< meta http-equiv =content-typecontent =text / html; charset = UTF-8>
< title> UDP聊天< /标题>
<! - 包括JQuery只是为了简化事情 - >
< script src =// ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\"> ;</script>
< script type =javascript / text>
var chat_room_id = undefined;
var last_received = 0;
$ b / **
*初始化聊天:
* - 设置房间ID
* - 生成html元素(聊天框,表单和输入等)
* - 与服务器
同步* @param chat_room_id聊天室的ID
* @param html_el_id聊天html应该放置的html元素的ID
* @return
* /
函数init_chat(chat_id,html_el_id){
chat_room_id = chat_id;
layout_and_bind(html_el_id);
sync_messages();
}

/ **
*询问服务器是发送到房间的最后一条消息,并将其存储为标识。
*这用于在加入用户时不要求完整的
*消息列表,只是登录后发送的消息。
* @return
* /
函数sync_messages(){
$ .ajax({
type:'POST',
data:{id:window.chat_room_id},
url:'/ chat / sync /',
dataType:'json',
success:function(json){
last_received = json.last_message_id;
}
});

setTimeout(get_messages(),2000);
}
$ b $ / **
*生成聊天框的HTML并绑定ajax事件
* @param target_div_id将聊天的html元素的id放置
* /
函数layout_and_bind(html_el_id){
//布局内容
var html ='< div id =chat-messages-container>'+
'< div id =chat-messages> < / div>'+
'< div id =chat-last> < / div>'+
'< / div>'+
'< form id =chat-form>'+
'< input name =message type =textclass =message/>'+
'< input type =submitvalue =Say/>'+
'< / form>' ;

$(#+ html_el_id).append(html);

// event stuff
$(#chat-form)。submit(function(){
var $ inputs = $(this).children('input' );
var values = {};

$ inputs.each(function(i,el){
values [el.name] = $(el).val( );
});
values ['chat_room_id'] = window.chat_room_id;

$ .ajax({
data:values,
dataType :'json',
type:'post',
url:'/ chat / send /'
});
$('#chat-form .message') .val('');
return false;
});
};
$ b / **
*从服务器获取消息列表并将消息附加到聊天箱
* /
function get_messages(){
$ .ajax({
type:'POST',
data:{id:window.chat_room_id,offset:window.last_received},
url:'/ chat / receive /',
dataType:'json',
成功:函数(json){
var scroll = false;

//首先检查我们是否在div的底部,如果是的话,一旦内容被添加,我们将滚动
var $ containter = $(#chat-messages-container);
if($ containter.scrollTop()== $ containter。 attr(scrollHeight) - $ containter.height())
scroll = true;

//添加消息
$ .each(json,function(i,m) {
if(m.type =='s')
$('#chat-messag es')。append('< div class =system>'+ replace_emoticons(m.message)+'< / div>');
else if(m.type =='m')
$('#chat-messages')。append('< div class =message>< div class =author >'+ m.author +'< / div>'+ replace_emoticons(m.message)+'< / div>');
else if(m.type =='j')
$('#chat-messages')。append('< div class =join>'+ m.author +'has加入< / DIV>');
else if(m.type =='l')
$('#chat-messages')。append('< div class =leave>'+ m.author +'has左< / DIV>');

last_received = m.id; (滚动)
$(#chat-messages-container)。animate({scrollTop:$(
))

//滚动到底部
#chat-messages-container)。attr(scrollHeight)},500);
}
});

//等待下一个
setTimeout(get_messages(),2000);

$ b / **
*告诉聊天应用我们加入
* /
函数chat_join(){
$。 ajax({
async:false,
type:'POST',
data:{chat_room_id:window.chat_room_id},
url:'/ chat / join /',
});

$ b / **
*告诉聊天应用我们要离开
* /
函数chat_leave(){
$。 ajax({
async:false,
type:'POST',
data:{chat_room_id:window.chat_room_id},
url:'/ chat / leave /',
});
}

//附加连接并离开事件
$(window).load(function(){chat_join()});
$(window).unload(function(){chat_leave()});
$ b $ //表情符号
var emoticons = {
'>:D':'emoticon_evilgrin.png',
':D':'emoticon_grin.png' ,
'= D':'emoticon_happy.png',
':\\''':'emoticon_smile.png',
':O':'emoticon_surprised.png',
':P':'emoticon_tongue.png',
':\\(':'emoticon_unhappy.png',
':3':'emoticon_waii.png',
'; \\)':'emoticon_wink.png',
'\\(ball \\)':'sport_soccer.png'
}

/ **
*正则表达式maddness !!!
*将上面的字符串替换为它们的img对象
* /
函数replace_emoticons(text){
$ .each(表情,函数(char,img){
re = new RegExp(char,'g');
//根据需要替换以下内容
text = text.replace(re,'< img src =/ media / img / silk /' + img +'/>');
});
返回文本;
}
< / script>
< / head>
< body>
< div id =chat>
< / div>

< script type =text / javascript>
$(window).ready(function(){
var chat_id = 1;
init_chat({{chat_id}},chat);
})
< / script>
< / body>
< / html>

当我在 Firefox 中加载页面时,我得到:

  ReferenceError:init_chat未定义
init_chat({{chat_id}},chat);

然而,函数 init_chat 是明确定义的。我究竟做错了什么?
我为该页面创建了 jsFiddle

解决方案

当您在头部部分中定义函数并调用它们时,会发生这种情况, 文档尚未初始化。移动脚本部分,在那里进行初始化并试用它。



由于您正在使用 jQuery ,如果你可以初始化变量并把整个脚本放在一个函数下并在 document 的就绪状态下调用该函数,它也会更好,可能会起作用。

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b init_chat({{chat_id}},chat);
//这里有什么错误,它真的是{{}}中的chat_id?
});


I'm trying to create a Javascript chat, with Python on the backend. This is the code I'm using ...

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>UDP Chat</title>
  <!-- including JQuery just to simplify things -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script type="javascript/text">
    var chat_room_id = undefined;
    var last_received = 0;

    /**
     * Initialize chat:
     * - Set the room id
     * - Generate the html elements (chat box, forms & inputs, etc)
     * - Sync with server
     * @param chat_room_id the id of the chatroom
     * @param html_el_id the id of the html element where the chat html should be placed
     * @return
     */
    function init_chat(chat_id, html_el_id) {
        chat_room_id = chat_id;
        layout_and_bind(html_el_id);
        sync_messages();
    }

    /**
     * Asks the server which was the last message sent to the room, and stores it's id.
     * This is used so that when joining the user does not request the full list of
     * messages, just the ones sent after he logged in.
     * @return
     */
    function sync_messages() {
        $.ajax({
            type: 'POST',
            data: {id:window.chat_room_id},
            url:'/chat/sync/',
            dataType: 'json',
            success: function (json) {
                last_received = json.last_message_id;
            }
        });

        setTimeout("get_messages()", 2000);
    }

    /**
     * Generate the Chat box's HTML and bind the ajax events
     * @param target_div_id the id of the html element where the chat will be placed
     */
    function layout_and_bind(html_el_id) {
            // layout stuff
            var html = '<div id="chat-messages-container">'+
            '<div id="chat-messages"> </div>'+
            '<div id="chat-last"> </div>'+
            '</div>'+
            '<form id="chat-form">'+
            '<input name="message" type="text" class="message" />'+
            '<input type="submit" value="Say"/>'+
            '</form>';

            $("#"+html_el_id).append(html);

            // event stuff
            $("#chat-form").submit( function () {
                var $inputs = $(this).children('input');
                var values = {};

                $inputs.each(function(i,el) {
                    values[el.name] = $(el).val();
                });
                values['chat_room_id'] = window.chat_room_id;

                $.ajax({
                    data: values,
                    dataType: 'json',
                    type: 'post',
                    url: '/chat/send/'
                });
                $('#chat-form .message').val('');
                return false;
        });
    };

    /**
     * Gets the list of messages from the server and appends the messages to the chatbox
     */
    function get_messages() {
        $.ajax({
            type: 'POST',
            data: {id:window.chat_room_id, offset: window.last_received},
            url:'/chat/receive/',
            dataType: 'json',
            success: function (json) {
                var scroll = false;

                // first check if we are at the bottom of the div, if we are, we shall scroll once the content is added
                var $containter = $("#chat-messages-container");
                if ($containter.scrollTop() == $containter.attr("scrollHeight") - $containter.height())
                    scroll = true;

                // add messages
                $.each(json, function(i,m){
                    if (m.type == 's')
                        $('#chat-messages').append('<div class="system">' + replace_emoticons(m.message) + '</div>');
                    else if (m.type == 'm')
                        $('#chat-messages').append('<div class="message"><div class="author">'+m.author+'</div>'+replace_emoticons(m.message) + '</div>');
                    else if (m.type == 'j')
                        $('#chat-messages').append('<div class="join">'+m.author+' has joined</div>');
                    else if (m.type == 'l')
                        $('#chat-messages').append('<div class="leave">'+m.author+' has left</div>');

                    last_received = m.id;
                })

                // scroll to bottom
                if (scroll)
                    $("#chat-messages-container").animate({ scrollTop: $("#chat-messages-container").attr("scrollHeight") }, 500);
            }
        });

        // wait for next
        setTimeout("get_messages()", 2000);
    }

    /**
     * Tells the chat app that we are joining
     */
    function chat_join() {
        $.ajax({
            async: false,
            type: 'POST',
            data: {chat_room_id:window.chat_room_id},
            url:'/chat/join/',
        });
    }

    /**
     * Tells the chat app that we are leaving
     */
    function chat_leave() {
        $.ajax({
            async: false,
            type: 'POST',
            data: {chat_room_id:window.chat_room_id},
            url:'/chat/leave/',
        });
    }

    // attach join and leave events
    $(window).load(function(){chat_join()});
    $(window).unload(function(){chat_leave()});

    // emoticons
    var emoticons = {
        '>:D' : 'emoticon_evilgrin.png',
        ':D' : 'emoticon_grin.png',
        '=D' : 'emoticon_happy.png',
        ':\\)' : 'emoticon_smile.png',
        ':O' : 'emoticon_surprised.png',
        ':P' : 'emoticon_tongue.png',
        ':\\(' : 'emoticon_unhappy.png',
        ':3' : 'emoticon_waii.png',
        ';\\)' : 'emoticon_wink.png',
        '\\(ball\\)' : 'sport_soccer.png'
    }

    /**
     * Regular expression maddness!!!
     * Replace the above strings for their img counterpart
     */
    function replace_emoticons(text) {
        $.each(emoticons, function(char, img) {
            re = new RegExp(char,'g');
            // replace the following at will
            text = text.replace(re, '<img src="/media/img/silk/'+img+'" />');
        });
        return text;
    }  
    </script>
</head>
<body>
  <div id="chat">
  </div>

  <script type="text/javascript">
    $(window).ready(function(){
       var chat_id = 1;
       init_chat({{ chat_id }}, "chat");
    })
  </script>
</body>
</html>

When I load the page in Firefox, I get:

ReferenceError: init_chat is not defined    
init_chat({{ chat_id }}, "chat");

However, the function init_chat is clearly defined. What am I doing wrong? I created a jsFiddle for the page.

解决方案

This happens when you define the functions in the head part and call them, when the document is not yet initialized. Move the script part, where the initialization happens and try it out.

Since you are using jQuery, it would also be better, if you can initialize the variables and enclose the whole script under a function and call the function inside document's ready state, it would probably work.

$(document).ready(function(){
   var chat_id = 1;
   init_chat({{ chat_id }}, "chat");
   // Something wrong here. Is it really chat_id inside {{ }}?
});

这篇关于ReferenceError:函数未定义 - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆