最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - jQuery: Execute function on document.ready() and window.load() - Stack Overflow

matteradmin4PV0评论

I'm trying to execute a jQuery function twice. Once when the DOM is ready, and then again when the page loads. Most of the time the second call isn't necessary, but every once in a while it is. Here is my code:

$(document).ready(function() {
    function someFunction() {
        alert('function plete');
    }
});

$(window).load(function() {
    someFunction();
});​

What am I doing wrong?

I'm trying to execute a jQuery function twice. Once when the DOM is ready, and then again when the page loads. Most of the time the second call isn't necessary, but every once in a while it is. Here is my code:

$(document).ready(function() {
    function someFunction() {
        alert('function plete');
    }
});

$(window).load(function() {
    someFunction();
});​

What am I doing wrong?

Share Improve this question asked May 4, 2012 at 15:59 colindunncolindunn 3,16311 gold badges50 silver badges73 bronze badges 1
  • As said, it's a scope thing, but you could basically just move your .load() event binding into the DOM Ready callback function and add another call to someFunction() directly :) – jave.web Commented Jun 5, 2019 at 15:14
Add a ment  | 

3 Answers 3

Reset to default 5

you are defining someFunction in the function you pass to $(document).ready()...the scope of the function should be outside it... try this:

function someFunction() {
    alert('function plete');
}

$(document).ready(someFunction);
$(window).load(someFunction);​

Try this instead:

function someFunction() {
    alert('function plete');
}

$(document).ready(function() {
    someFunction();
});

$(window).load(function() {
    someFunction();
});

someFunction is not accessible within the $(window).load because it's scope is limited to the document.ready. Take it out of the document.ready and put it in the global context.

function someFunction() {
        alert('function plete');
}

$(document).ready(function() {
     someFunction(); 
});

$(window).load(function() {
    someFunction();
});​
Post a comment

comment list (0)

  1. No comments so far