简体   繁体   中英

jQuery: sharing function between page code and document.ready code

I have some nice dialogues defined as such in jQuery:

<script type="text/javascript">
$(document).ready(function() {

    $( "#someDialog" ).dialog({
        autoOpen: false,
        model: true,
        buttons: {
            "Do Something": function() {
                var cleanInput = sanitizeInput(input);
                // Do something with the clean input
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
        }
    });

    function sanitizeInput(input) {
        // Some magic here
        return input;
    }
});
</script>

Somewhere in the page, unrelated to the dialog, I have an element that calls a function with a parameter:

<a href="#" onclick="doSomething('wendy');">Wendy's stats</a>

And the associated JavaScript:

<script type="text/javascript">

function doSomething(input) {
    var cleanInput = sanitizeInput(input);
    // Some code here
}

</script>

I would like to reuse the sanitizeInput() function for this function as well. However, from outside the document.ready function, the dialog does not work. Putting the doSomething() function inside the document.ready function breaks it likewise. So where do I put the sanitizeInput() function such that both can use it?

Thanks.

You just need to move the function outside the ready() callback.

$(document).ready(function() {

    $( "#someDialog" ).dialog({
        autoOpen: false,
        model: true,
        buttons: {
            "Do Something": function() {
                var cleanInput = sanitizeInput(input);
                // Do something with the clean input
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
        }
    });
});

  /*** Make it global ***/
function sanitizeInput(input) {
    // Some magic here
    return input;
}

Now sanitizeInput() is globally available instead of confined to the variable scope of the ready() callback.

Additionally, I would suggest some small changes.

First of all, I would replace this:

<a href="#" onclick="doSomething('wendy');">Wendy's stats</a>

with:

<a href="#" data-name="wendy or server var">Wendy's stats</a>

and then add this to the end of the $(document).ready block:

$("a[data-name]").click(function (e) {
    e.preventDefault();
    doSomething($(this).data("name"));
});

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