调用Jquery函数不起作用

时间:2015-04-21 22:42:43

标签: javascript jquery html css

我目前正在关注一个教程,本教程中的人员正在将css,html和jquery编码在一个文件中。我把它们分成了单独的文件。我的问题是教程中的代码在调用函数时起作用而我的函数没有,即使代码完全相同。这是我的一些代码

//Jquery File

function username(){
    $("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}


$(function(){

username();

    $("#textbox").keypress(function(event){

........

HTML文件

<div id = "container">

</div>

<div id = "controls">
.....

教程代码

<script type="text/javascript">
function username(){
    $("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}

$(function(){

    username();

    $("#textbox").keypress(function(event){

.......

它完全相同但由于某些原因我的代码不起作用,我测试了两者。我知道我链接到正确的jQuery文件,因为我的其他功能正常工作没问题。

完整的HTMl                       JQuery Chatbot教程                                                   

jQuery Chatbot v.1.0教程

    

<div id = "container">

</div>

<div id = "controls">
    <textarea id = "textbox" placeholder = "Enter your message here..."></textarea>
    <button id = "send">Send</button>
    <br>
    <input checked type = "checkbox" id = "enter"/>
    <label>Send on enter</label>
</div>

    <script type="text/javascript" src="jquery-1.11.2.min.js"></script>
    <script type="text/javascript" src="chatbot.js"></script>
</body>

完整的JQuery文件

function username(){
    $("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}



$(function(){

username();

    $("#textbox").keypress(function(event){
        if ( event.which == 13){
            if ( $("#enter").prop("checked") ){

                $("#send").click();
                event.preventDefault();

            }

        }

    });
        });


    $("#send").click(function(){

        var username = "<span class ='username' = >You: </span>";

        var newMessage = $("#textbox").val();

        $("#textbox").val("");

        var prevState = $("#container").html();

        if (prevState.length > 3){
            prevState = prevState + "<br>";
        }

        $("#container").html(prevState + username + newMessage);

        $("#container").scrollTop($("#container").prop("scrollHeight"));

    });

1 个答案:

答案 0 :(得分:-2)

调用前代码中可能有错误。尝试:

$(function(){
  alert('Debug me 2');
  username();
  alert('Debug me 2');
...

看看会发生什么。

相关问题