jQuery script BEFORE HTML elements
Is it possible for jQuery to bind events to elements if the jQuery script block comes before the html tags in the page?
As an example, this does not work:
<script>
$('a').bind('click', function() {
alert($(this).attr("innerHTML"));
</script>
<a href="#He开发者_如何学编程llo">Greetings</a>
Yes, I could just put the script after the elements, but hey, maybe I don't wanna. Just curious if this is the only way.
Yes, if you put the code in a ready
[docs] event handler (and fix your syntax errors ;)):
$(function() {
$('a').bind('click', function() {
alert(this.innerHTML);
// jQuery way would be: $(this).html()
});
});
Another way is to execute the script during $(window).load()
event
$(window).load(function() {
$('a').bind('click', function() {
alert($(this).attr("innerHTML"));
});
Now the bind
will occur once all the document is fully loaded.
Use jQuery ready function : http://api.jquery.com/ready/
<script>
$(document).ready(function() {
$('a').bind('click', function() {
alert($(this).attr("innerHTML"));
}
</script>
<a href="#Hello">Greetings</a>
Note that instead of using $(this).attr("innerHTML")
you can simply do $(this).html()
Yes, but wrap the code in $(function() { ... }) to tell jquery to execute it once the Dom is fully loaded, at which point all elements will be available.
精彩评论