简体   繁体   中英

Jquery function is being called on load

I have some jquery which I want to run on load time but It doesn't seem to hit the load event. Here is my jquery

$(function () {
    $('.field-of-work').load(function () {
        var $wrapper = $(this).closest('.field-of-work-wrapper');

        $wrapper.find('.position').hide();
        $wrapper.find('.position').find('select').val('');

    });
});

Why would the load event not get hit?

Try to use ready() method:

$(document).ready(function(){
    $('.field-of-work select').load(function () {
        var $wrapper = $(this).closest('.field-of-work-wrapper');

        $wrapper.find('.position').hide();
        $wrapper.find('.position').find('select').val('');

    });
});

$(function() is an alias for $(document).ready(function(){}) and your load event is fired before the document ready event.

If you want your code inside the load listener to fire on page loading, you should put it outside of any $(function() or $(document).ready() like this :

$('.field-of-work').on('load', function () {
    var $wrapper = $(this).closest('.field-of-work-wrapper');

    $wrapper.find('.position').hide();
    $wrapper.find('.position').find('select').val('');

});

$(function(){
   /* Your other code here */
});

try this :

 $(document).ready(function() {
    $('.field-of-work').load(function () {
        var $wrapper = $(this).closest('.field-of-work-wrapper');

        $wrapper.find('.position').hide();
        $wrapper.find('.position').find('select').val('');

    });
});

Do you use the Load function correctly?

Load requires an "url" as a parameter and returns the HTML into the matched element.

http://api.jquery.com/load/

Description: Load data from the server and place the returned HTML into the matched element.

load( url [, data ] [, complete ] )Returns: jQuery

Do you want to perform the actions inside your load method right after the page has been loaded?

You may want to use "ready()" instead of it:

$(document).ready(function() {

       var $wrapper = $(this).closest('.field-of-work-wrapper');

        $wrapper.find('.position').hide();
        $wrapper.find('.position').find('select').val('');
});

Or did you just want to add an Event Handler load to it (like

.on( "load", handler ).

http://api.jquery.com/load-event/

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