当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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"));
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: