开发者

Run code once on page load, then every time a button is clicked

开发者 https://www.devze.com 2023-02-03 22:00 出处:网络
I need to have a function run once when the page is loaded, and then again whenever a button is pressed.If I take out the code to run it on page load, it works whenever the button is pressed, otherwis

I need to have a function run once when the page is loaded, and then again whenever a button is pressed. If I take out the code to run it on page load, it works whenever the button is pressed, otherwise it only runs once on page load and never when the button is pressed.

$(function()
{
    // code to be run
});

$(document).ready(function()
{
    $("#b开发者_C百科utton").click(function()
    {
        // code to be run
    });
});


function run(){
    //code to run
}
$(document).ready(function()
{
    $("#button").click(function()
    {
        run()
    });
    run()
});


Define a function:

$(function() {
    var your_code = function() {
        // code to be run
    };
    $("#button").click(your_code);
    your_code();
});

Working Example.

0

精彩评论

暂无评论...
验证码 换一张
取 消