Conditional if statements in jQueryUI?

I have a JavaScript function that passes an argument that opens the jQueryUI dialog. I want the dialog to have one or two buttons based on the value of the argument. How can I do it?

So far I have 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 them completely broke my page.

+4
source share
2 answers

buttons is a literal JavaScript object. You can 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 }); } 
+3
source

A general way to do this is as follows:

 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 in which you can make decisions, and then return the result that you decide.

+1
source

Source: https://habr.com/ru/post/1309359/


All Articles