我可以将这个功能分成两部分吗?

时间:2012-08-19 12:57:39

标签: javascript jquery

我的代码包含类似于以下内容的代码。我可以在屏幕上一次打开一个或多个模态。这是代码的版本。在实际的应用程序中有更多,所以我想将这个功能分成两部分:

function openModal(oLink, content) {
    var btns = {
        'Close': function (win) {
            modal.closeModal()
        }
    }
    var modal = $.modal({
        buttons: btns
    });
}

我可以将它分成两个这样的函数:

function btnsModal() {
    var btns = {
        'Close': function (win) {
            modal.closeModal()
        }
    }
    return btns;
}

function openModal(oLink, content) {
    var btn = btnsModal();
    var modal = $.modal({
        buttons: btn
    });
}

当我尝试这个时,我得到错误:

Object doesn't support property or method 'closeModal' 

第一个脚本是否只能工作,因为modal是在与使用modal.closeModal()的文件相同的文件中定义的?

3 个答案:

答案 0 :(得分:0)

你可以缓存模态(var modal = $ .modal ...)并在两个函数之前定义它。

var modal = $.modal

function btnsModal()

function openModal()

答案 1 :(得分:0)

以下是如何获得所需内容的示例:

function createModal(options) {

    // create your modal and use the options passed
    // like options.message, and options.title for example
    // here you will set its default behavior

}

// calling it
createModal({
    message: "This is the message".
    title: "A modal"
});

以下是jQuery UI的一个示例,您可以轻松地将其更改为您需要的内容。我只是使用jQuery UI来简化构建示例,因为我没有你的$ .modal方法。

<强> HTML:

<button id="btn1" type="button">Open Modal 1</button>
<button id="btn2" type="button">Open Modal 2</button>

<强> JavaScript的:

    $(function() {

    $( "#btn1" ).click(function(){
        createModal({
            title: "Title!",
            message: "This is a Dialog!"
        });
    });

    $( "#btn2" ).click(function(){
        createModal({
            title: "Another Title!",
            message: "This is another Dialog!"
        });
    });

    function createModal( options ) {

        var $div = $( "<div></div>" );
        $div.append( $( "<p></p>" ).html( options.message ) );

        $div.dialog({
            modal: true,
            title: options.title,
            buttons: {
                "Foo": function() {
                    $(this).dialog( "close" );
                },
                "Bar": function() {
                    $(this).dialog( "close" );
                }
            },
            close: function( event, ui ) {
                // as the container was created on-the-fly
                // we need to do this to destroy the container
                $(this).dialog( "destroy" );
            }
        });

    }

});

实例:http://jsfiddle.net/davidbuzatto/ZJzky/

答案 2 :(得分:0)

你需要在函数范围之外声明变量“modal”,以便在两个函数中都可以访问。

var modal;
function btnsModal() {
    var btns = {
        'Close': function (win) {
            modal.closeModal()
        }
    }
    return btns;
}

function openModal(oLink, content) {
    var btn = btnsModal();
    modal = $.modal({
        buttons: btn
    });
}
相关问题