jQuery简单按钮绑定

jQuery simple button bind

本文关键字:绑定 按钮 简单 jQuery      更新时间:2023-09-26

我是jQuery的新手,所以这应该是一个简单的问题。

据我所知,我可以使用绑定一个方法来监听事件,比如点击按钮

$('#buttonID').bind('click', function (){//some code});

然而,这对我不起作用,所以我一定做错了什么。

这是我的简单html文件:

        <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
    <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js'></script>
    <script src='test.js'></script>
    </head>
    <body>
    <input id="SignIn" type="button" value="Sign In"></input>
    </body>
    </html>

除了加载jQuery文件外,它还加载文件test.js,如下所示:

// JavaScript Document
$('#SignIn').bind('click', function() {alert('hi');});

这还不够装订吗?我希望这会触发一个警报对话框,但它没有,似乎根本没有执行回调。

这里怎么了?两个文件(html和js)都位于同一个目录中,Google Chrome不会抱怨JavaScript控制台中的任何内容,因此从那以后,一切都应该很好。

谢谢你的帮助!

将代码包装在文档就绪处理程序中。它接受一个在DOM完全加载时执行的函数。

当您使用jQuery 1.3 时

$(document).ready(function() {
    $('#SignIn').bind('click', function() {
        alert('hi');
    });
});

对于jQuery 1.7+,

$(document).ready(function() {
    $('#SignIn').on('click', function() {
        alert('hi');
    });
});

此外,从jQuery 1.7开始,.on()方法是将事件处理程序附加到文档的首选方法。

$(function(){
    $('#SignIn').bind('click', function() {alert('hi');});
})

尝试

$(function(){
   $('#SignIn').click(function() {alert('hi');});
});

将您的Javascript移动到HTML页面的底部,就在结束body标记的正上方。

这样,DOM在加载时就准备好了,不需要$(document).ready()调用。

https://developer.yahoo.com/performance/rules.html#js_bottom

您可能希望在最底部包含JavaScript文件,并且一切都应该按预期工作。建议执行此操作,并在顶部(head标记)包含CSS文件。有关更多信息,请参阅@Grim提供的链接。。。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<input id="SignIn" type="button" value="Sign In"></input>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js'></script>
<script src='test.js'></script>
</body>
</html>
$( "#target" ).click(function() {
//Write some code here
});

你可以试试这个。

$(document).ready(function(){
  $('#SignIn').on('click', function() {alert('hi');});
});

您可以使用它。

  • $(document).ready(function () { $("#SignIn").click(function () { alert('demo'); }); });