When using jQuery UI the buttons for a mo开发者_开发知识库dal can be set-up after init like so:
$( ".selector" ).dialog( "option", "buttons", { "Ok": function() { $(this).dialog("close"); } } );
However what I'd like to do is add multiple buttons, dependent on logic conditions:
if ( canClose ){
$( ".selector" ).dialog( "option", "buttons", { "Ok": function() { $(this).dialog("close"); } } );
}
if ( canAlert ){
$( ".selector" ).dialog( "option", "buttons", { "Ok": function() { alert('Hello'); } } );
}
However the above code won't work correctly, as it resets the buttons array each time.
How can I add X number of buttons using logic, without loosing any existing buttons?
Try it like this:
var buttons = {};
if (canClose) {
buttons.Close = function() { $(this).dialog("close"); }
}
if (canAlert) {
buttons.Alert = function() { alert('Hello'); }
}
$(".selector" ).dialog( "option", "buttons", buttons );
Thus you only create the dialog once. Of course, the buttons need two different names, otherwise the second one will overwrite the first one. But then, not having several buttons with the same text, that's just good GUI design. ;)
Use the buttons array option to create both buttons:
if ( canClose && canAlert )
$( ".selector" ).dialog( "option", "buttons", [
{
text: "Ok",
click: function() { $(this).dialog("close"); }
},
{
text: "Ok",
click: function() { alert('Hello'); }
}
] );
I've managed to achieve my aim by creating an array upfront, then assigning this to the modal buttons property:
var buttons = new Array();
if ( occurance.canEdit ){
buttons[buttons.length] = { text: "Edit", click: function(){ editOccurance(data[0],data[1]); } };
}
if ( occurance.canDelete ){
buttons[buttons.length] = { text: "Delete", click: function(){ deleteOccurance(data[0],data[1]); } };
}
$( "#dialogOccurance" ).dialog( "option", "buttons", buttons );
精彩评论