开发者

Conditional If statements within jQueryUI's options?

开发者 https://www.devze.com 2022-12-29 16:16 出处:网络
I have a JavaScript function that I\'m passing an argument to, that opens a jQueryUI Dialog. I want the dialog to have either one or two buttons, based on the value of the argument. How should I do th

I have a JavaScript function that I'm passing an argument to, that opens a jQueryUI Dialog. I want the dialog to have either one or two buttons, based on the value of the argument. How should I do this?

So far I've tried:

function foo(hasFile) {
    $('#dialog').dialog({
        buttons: {
            Close: function() { $(this).dialog('close'); },
            if (hasFile)
                "Download": // do something
    }
    });
}

and

function foo(hasFile) {
    $('#dialog').dialog({
        buttons: 
            if (hasFile)
          开发者_运维百科  {
                "Download": // do something
                Close: function() { $(this).dialog('close'); }
            }
            else
            {
                Close: function() { $(this).dialog('close'); }
            }
    });
}

both of which have thoroughly broken my page.


buttons is a JavaScript literal object. You could do something like this:

function foo(hasFile) {
    var buttons = {
        Close: function() { $(this).dialog('close'); }
    };

    if (hasFile) {
        buttons.Download = function(){
            // Do something.
        };
    }
    $('#dialog').dialog({
        buttons: buttons
    });
}


A general way to do that is like this:

foo.dialog({
  // ...
  buttons: (function() {
    function CloseHandler() {
      // close ...
    };
    function DownloadHandler() {
      // download ...
    };

    return condition ?
      { "Download": DownloadHandler, "Close": CloseHandler } :
      { "Close": CloseHandler };
  })(),
  // ...
});

The idea is that you create a function where you can make decisions, and then return the result you decide upon.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号