简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM