jQuery:在页面代码和document.ready代码之间共享功能

时间:2012-01-15 16:27:08

标签: javascript jquery

我在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>

在页面的某个地方,与对话框无关,我有一个元素调用带参数的函数:

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

以及相关的JavaScript:

<script type="text/javascript">

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

</script>

我也想为这个函数重用sanitizeInput()函数。但是,从document.ready函数外部,该对话框不起作用。将doSomething()函数放在document.ready函数中会同样破坏它。那么我在哪里放置sanitizeInput()函数,以便两者都可以使用它?

感谢。

2 个答案:

答案 0 :(得分:3)

您只需要将功能移到ready()回调之外。

$(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;
}

现在sanitizeInput()是全局可用的,而不是局限于ready()回调的变量范围。

答案 1 :(得分:2)

另外,我会建议一些小改动。

首先,我会替换它:

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

使用:

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

然后将其添加到$(document).ready块的末尾:

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