在页面加载时运行一次代码,然后每次单击一个按钮 [英] Run code once on page load, then every time a button is clicked

查看:81
本文介绍了在页面加载时运行一次代码,然后每次单击一个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在加载页面时运行一次函数,然后在按下按钮时再运行一次。如果我在页面加载时取出代码来运行它,它会在按下按钮时起作用,否则它只在页面加载时运行一次,而不是在按下按钮时运行。

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()
{
    $("#button").click(function()
    {
        // code to be run
    });
});


推荐答案

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

这篇关于在页面加载时运行一次代码,然后每次单击一个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆