0

嗨,我是 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>
4

3 回答 3

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

于 2013-08-23T06:38:26.890 回答
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>

现场演示

于 2013-08-23T06:39:08.140 回答
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>
于 2013-08-23T06:39:17.827 回答