0

我可以知道为什么当我单击按钮时alert('clicked')没有出现以下内容吗?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title></title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script src="Base64.js" type="text/javascript"></script>
        <script type="text/javascript">
            $("#Button1").click(function () {
                alert('clicked');
            });
        </script>
    </head>

    <body>
        <form name="input" action="">Username:
            <input type="text" id="username" value="" />
            <br />Password:
            <input type="text" id="password" value="" />
            <br />
            <input type="button" id="Button1" value="Submit" />
            <div>Login Test 1.htm</div>
        </form>
    </body>

</html>
4

4 回答 4

6

当脚本执行时,按钮在 DOM 中还不存在。等到 DOM 准备好jQuery.ready

$(document).ready(function() {
    $("#Button1").click(function(){alert('clicked');});
});

或者,您可以在添加按钮后在某处运行脚本:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title></title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script src="Base64.js" type="text/javascript"></script>
    </head>

    <body>
        <form name="input" action="">Username:
            <input type="text" id="username" value="" />
            <br />Password:
            <input type="text" id="password" value="" />
            <br />
            <input type="button" id="Button1" value="Submit" />
            <div>Login Test 1.htm</div>
        </form>
        <script type="text/javascript">
            $("#Button1").click(function () {
                alert('clicked');
            });
        </script>
    </body>

</html>
于 2012-06-21T02:39:33.847 回答
3

尝试这个 ,

$(document).ready(function () {
    $("#Button1").click(function(){
        alert('clicked');
    });
});
于 2012-06-21T02:41:34.093 回答
0

你应该用 jQuery 语句包围$(function() { ... });

于 2012-06-21T02:40:59.573 回答
0

工作演示 http://jsfiddle.net/69v27/4/

请尝试在您的代码中采购 Jquery,如下所示:

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>

代码

$(document).ready(function() {

    $("#Button1").click(function() {
        alert('clicked');
    });

});​
于 2012-06-21T02:39:45.093 回答