开发者

JQuery click function not getting called

I have a simple page for testing with only a button, I am linking to an external js file. It is displaying the jquery version in a alert box, but when the button is clicked nothing happens. What is wrong with this?

Here is my simple test html page

<title>Insert title here</title>开发者_运维百科
<!-- scripts -->
<script language="JavaScript" type="text/javascript" src="jquery.js"></script>
<script language="JavaScript" type="text/javascript" src="myscript.js"></script>
</head>
<body>
<form>
    <input  type="button"  tabindex="5"  value="jscript" id="testbutton" />
</form>
</body>

and here is my myscript file content

alert($.fn.jquery);
$('#testbutton').click(function(){
alert("test successful");
});

I am using JQuery version 1.6


Probably because the DOM is not ready for JavaScript processing at the time of bindiing the click handler. Try:

$(document).ready(function() {
    $('#testbutton').click(function(){
        alert("test successful");
    });
});


You need a document.ready:

$(document).ready(function(){
  alert($.fn.jquery);
  $('#testbutton').click(function(){
    alert("test successful");
  });
});

That's because your #testbutton can't be referenced until it's loaded

Hope this helps. Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜