我简单的jQuery代码无效。我运行它时会得到一个空白页面

时间:2013-08-23 06:37:32

标签: javascript jquery html

您好我是javascript的新手。我写了一个简单的jQuery代码,但它没有用。我运行它时会得到一个空白页面。有人可以帮助我吗

    <html>
    <head>
    <script type = "text/javascript" src="http://code.jquery.com/jquery-1.9.1.js">
    </script>
    </head>

    <body>
    <script type = "text/javascript">
    <div id = "myElement">
    <input id = "click" type = "button" value = "Click">
    </div>
    $(document).ready(function()
    {
        function sayHello(){
            alert("Hello jQuery");
        }

    $("#click").bind("button",sayHello);

    });
    </script>
    </body>
    </html>

3 个答案:

答案 0 :(得分:2)

你在脚本元素中有html标记,你还需要绑定事件click

<html>
    <head>
        <script type = "text/javascript" src="http://code.jquery.com/jquery-1.9.1.js">
        </script>
    </head>

    <body>
        <div id = "myElement">
            <input id = "click" type = "button" value = "Click"/>
        </div>
        <script type = "text/javascript">
            $(document).ready(function() {
                function sayHello(){
                    alert("Hello jQuery");
                }

                //$("#click").bind("click", sayHello); // the event is called click not bind
                $("#click").on("click", sayHello); // on is the preferred way to register event handler

            });
        </script>
    </body>
</html>

演示:Plunker

答案 1 :(得分:0)

您正在将JS代码与html元素混合使用。这不是事情的运作方式。将html元素从script移出,就像这样 -

<div id = "myElement">
    <input id = "click" type = "button" value = "Click">
</div>

<script type = "text/javascript">
    $(document).ready(function()
    {
        function sayHello(){
            alert("Hello jQuery");
        }

        $("#click").bind("click",sayHello);
    });
</script>

Live Demo

答案 2 :(得分:0)

<div id = "myElement">
    <input id = "click" type = "button" value = "Click">
    </div>

它不会进入脚本..它应该是它的...

<script type = "text/javascript">
 $(document).ready(function()
    {
        function sayHello(){
            alert("Hello jQuery");
        }

    $("#click").bind("button",sayHello);

    });
    </script>