Why this Jquery function does not display me an alert box?
I observed when I put the ready event the function works but as I remove it It does not..
Works.
<script type="text/javascript">
$(document).ready( function() {
$('.clicky').click( function() {
alert("TEst10");
$(this).addClass('clicked');
alert("TEst10");
setTimeout( function() {
$(this).removeClass('clicked');
}, 1000 );
});
});
</script>
Not work
<script type="text/javascript">
$('.clicky').click( function() {
alert("TEst10");
$(this).addClass('clicked');
alert("TEst10");
setTimeout( function() {
$(th开发者_开发知识库is).removeClass('clicked');
}, 1000 );
});
</script>
Why the second one does not work?
Because element with a class clicky
isn't in the DOM structure when your second code gets called.
The first one works because you wrapped the code in document.ready
function which gets invoked once the DOM is ready.
If you want to make the second code work just put the code in the script tag after the definition of element with class clicky
, preferably put the script at the end of the body
tag.
But why not just use document.ready
?
The second code probably runs before the browser finished loading the page, and the clicky
element does not exist yet. Common workarounds: run the code from an event handler which is called when the document finishes loading (just like your first example does it), put the script tag after the HTML tag it refers to, or use live to bind the click handler.
If your script tag is placed before you Target element you need to use doc ready. This is because the element must exist before you attach events to it.
Why don't you want to use doc ready? You could move the script tag down the page or use .live to bind the click
HTH!
The ready()
function is a handler. A function to execute after the DOM is ready.
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
More on .ready() on jquery site
精彩评论