简体   繁体   中英

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="#Hello">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()
    });
});

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()

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.

是的,但是将代码包装在$(function(){...})中,以告诉jquery在Dom完全加载后执行它,届时所有元素都将可用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM