简体   繁体   English

文档准备功能

[英]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: 您可以简单地将在ready函数上运行的代码重构为它自己的函数,然后在按钮的click事件中调用它:

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

function codeToRun(){
    // do work
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM