how to use Jquery writing a click event ? Which way is correct?
I'm new 开发者_如何学JAVAin Jquery. I have a problem in my code, i'm very confused that which way is correct when writing jquery code for click event. Please help me and explain thanks in advance !
first method :
<script type="text/javascript">
$('a').click(function(){
alert('you clicked a tag !!! ');
});
</script>
and second method :
<script type="text/javascript">
$(document).ready(function(){
$('a').click(function(){
alert('you clicked a tag !!! ');
});
});
</script>
when i write 2 method for testing, just the second one is successful and display a alert, but the first one do nothing. In addition i review on http://api.jquery.com/click/ the first one is the way they write sample but it run successfully, that make me confused .
<script>
$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
</script>
The reason the first one does not succeed, is that no a
elements has been loaded yet (provided your script is placed in the header of you page).
Using $(document).ready(..)
makes your code run when your DOM is ready for manipulation, allowing jQuery to attach the click-event to your a
-element.
In general, you should not start running DOM-manipulative code before the $(document).ready
event has fired, to make sure everything you need is available.
The first way runs your code right away, as soon as the browser reaches that part of the HTML.
The second way, it waits until the document is ready and then applies your code.
What is happening is that the DOM isn't fully loaded when the code written in the first way gets executed. This means there might not be any <a>
element to apply your code to. That's why it's preferred to use the second way (so that it executes when the DOM is ready).
You need to enclose all your jquery in $(document).ready() to ensure that all the resources loaded and DOM was processed before you start binding events.
However if you put your script tag at the bottom of your HTML page (without $(document).ready()) jQuery is likely to work as all the html and javascript loaded and the DOM was processed.
Best practice though is to enclose all your jquery in $(document).ready()
In the first example you're trying to bind the click event to links when the document is not ready. You have to use the second option if you need to perform anything DOM related.
In the first method, the element has to be declared first before the javascript. But In the second method, it does not matter because the javascript is run when the document is ready, i.e finished loading.
精彩评论