Use JavaScript variable as function name?

前端 未结 5 1038
抹茶落季
抹茶落季 2020-12-02 00:23

I have the following code in Javascript:

jQuery(document).ready(function(){
    var actions = new Object();
    var actions;
    actions[0] = \'create\';
            


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 00:47

    You need to combine SLaks' and RoToRa's answers:

    var actionNames = [ 'create', 'update' ];   //This creates an array with two items
    
    for (var i = 0; i < actionNames.length; i++) {
        window[ actionNames[i] + 'Dialog' ] = function() {
            $('#'+ actionNames[i] +'dialog').dialog('destroy');
            $('#'+ actionNames[i] +'dialog').dialog({
                resizable: false,
                height:600,
                width:400,
                modal: true,
                buttons: {
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });
        }
    }
    

    Since you're running this in the document ready event handler, the "this" variable would refer to the document, not the window.

提交回复
热议问题