简体   繁体   中英

Document.ready function

我在- $(document).ready(function() {-中有一些代码,这些东西会乱码,加载页面时会触发代码,但是我想做的是添加一个按钮,以便每次我运行此函数时按下按钮,我怎么能做到这一点,谢谢?

function shuffleStuffAround() {
    // truffle shuffle
}

$(function($) { // DOM ready
    shuffleStuffAround();

    $("#some-button").click(function() {
        shuffleStuffAround();
        return false; // you probably want this
    });
});

You can save you "shuffle stuff around" code as a function and call it from other parts of your codebase.

var foo = function() {
  // code that shuffles stuff around
};

$(document).ready(function() {
  foo();
  // other stuff
});

$('#mybutton').click(foo);
//or
$('#mybutton').click(function() {
  foo();
  // other stuff.
});

You could simple refactor the code that you run on the ready function into its own function and call that in your button's click event:

$(document).ready(function(){
    codeToRun();
    $('.button').click(function(){codeToRun()});
});

function codeToRun(){
    // do work
}

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