开发者

why doesn't my simple jquery work?

开发者 https://www.devze.com 2023-03-26 21:28 出处:网络
I\'m writing some simple jquery, and for some reason, I simply cannot make it work.I /know/ it works elsewhere, but I\'m either missing something, or there\'s a bug on my webserver.

I'm writing some simple jquery, and for some reason, I simply cannot make it work. I /know/ it works elsewhere, but I'm either missing something, or there's a bug on my webserver.

code follows:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>asdf</title>

    <script src="jquery.js" type ="text/javascript"></script>


<script language ="javascript" type = "text/javascript">
 //alert("number one");


$('#regSubmit').click(function(){

alert("Clicked!");

});

$('#test2').click(function(){
   alert("yeah that worked.");
})

</script>
</head>
<body>


<input type ="button" id="regSubmit" value="Register!" />

<div id="test2">
Here is some other stuff!
</div>


</body>
</html>

So I've copied 开发者_如何转开发that code exactly, but it doesnt work for me. that commented out alert near the top (number one) works fine, so its calling the jquery, but no clicks register.

What am I doing wrong?


add your javascript to

$(function(){
   //your code
});

demo

This is needed, as you can only bind events to elements, they are already exist. At the moment you try this before they exist, this example code executes it after the full page is loaded, so all html is there


Your code when embedded into HTML is executed sequentially, so at the time of the execution of your code regSubmit and test2 are not yet defined.

Move your code to the bottom of the HTML document, or wrap it in $(function(){ /*your code here*/ }); which will defer your code execution until the entire document is loaded.


You'll have to either move the script to the bottom or wrap it in $(document).ready(function() { … }. The document hasn't finished loading when the script executes, so when you try to attach the event handlers, the associated elements don't exist.


You are trying to bind events to elements before they exist. Run the code from the ready event handler so that it runs when the whole document has loaded:

$(document).ready(function(){

  $('#regSubmit').click(function(){
    alert("Clicked!");
  });

  $('#test2').click(function(){
    alert("yeah that worked.");
  })

});
0

精彩评论

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