JQuery events cannot be called with type="text/javascript"
For some reason, the following code will work:
The following code does not work:
<script type='text/javascript'>
$('#login_password').click(function() {
alert('Handler for .click() called.');
});
</script>
But it does when I do not specify the script type like so:
<script>
...
</script&g开发者_开发百科t;
Why do I need to leave the script type unspecified for event calls on elements?
Even more oddly, the following will work:
<script type='text/javascript'>
$(document).ready(function(){
$("#login_username").focus();
});
</script>
I am using JQuery 1.6.1 on Rails 3.0.9. The gem jquery-rails 1.0.12 is installed and bundled.
In my application.html.erb I call:
<%= javascript_include_tag 'application.js', 'jquery.min.js', 'jquery.rails.js' %>
Where jquery.rails.js is the unobtrusive scripting adapter https://github.com/rails/jquery-ujs
Thanks in advance!
Try wrapping your first example with $(document).ready like
<script type='text/javascript'>
$(document).ready(function(){
$('#login_password').click(function() {
alert('Handler for .click() called.');
});
});
</script>
See the comment from Kevin, he is right. The fact that is worked without specifying the type attribute is just timing luck or some browser-specific fluke.
It sounds like you are trying to execute a script on the DOM before the DOM is ready, which explains why the third snippet works fine.
If your scripts are loaded before the elements you're working with (e.g. including the scripts in the <head>
tag), be sure to wrap them like so:
$(document).ready(function() {
// manipulate DOM here
});
// or
jQuery(function($) {
// manipulate DOM here
});
精彩评论