2012-05-28 11 views
9

Mam modalny jQuery, gdzie chcę dodać dodatkowy przycisk, jeśli spełnione jest warunkowe oświadczenie.Przycisk warunkowy dodany do modemu jQuery

oryginalny przykładowy kod (nacięcia):

$("#dialog").html("<div></div>").dialog({ 
    title: "Some Title", 
    modal: true, 
    width: 550, 
    buttons: { 
     Ok: function() { 
      // 
     }, 
     'A Button': function() { 
      // 
     } 
    } 
}).dialog('open'); 

Więc jak widać powyżej jest modalne z 2 przyciskami, ale chcę też dodać tam jakiś dynamicznego kodu, aby móc zaspokoić dodatkowe przycisk, jeśli ustawiono zmienną. na przykład

var some_variable = 0; 

$("#dialog").html("<div></div>").dialog({ 
    title: "Some Title", 
    modal: true, 
    width: 550, 
    buttons: { 
     Ok: function() { 
      // 
     }, 
     'A Button': function() { 
      // 
     } 
     /* ??? */ 
     if (some_variable==1) //then add the other button's code here.. 
     /* ??? */ 
    } 
}).dialog('open'); 

Odpowiedz

16

Można by utworzyć obiekt buttons przed utworzeniem okna:

//Create the buttons object 
var buttons = { 
    Ok: function() {}, 
    'A Button': function() {} 
}; 

//Add another button to that object if some condition is true 
if(something) { 
    buttons['B button'] = function() {}; 
} 

//Create the dialog, passing in the existing buttons object 
$("#dialog").html("<div></div>").dialog({ 
    buttons: buttons, 
    //Other options 
}); 
3

Alternatywnie, można utworzyć wszystkie przyciski, których potrzebujesz, a następnie wyświetlić lub ukryć je w zależności od przypadku, oraz w zależności od tego, co dzieje się w Twoim oknie. Jednym z takich sposobów jest użycie zdarzenia tworzenia okna dialogowego jqueryui.

Można odwołać się do przykładu pracuje w: http://jsfiddle.net/eCLuy/

$("#dialog").dialog({ 
    buttons: { 
     'prev': { 
     text: 'prev', 
     id: "prevB", 
     click: function() { 
      $(this).closest(".ui-dialog").find(".ui-button#prevB").addClass("hidden");    
      $(this).closest(".ui-dialog").find(".ui-button#nextB").removeClass("hidden");    
     } 
     },   
     'next': { 
      text: 'next', 
      id: "nextB", 
      click: function() { 
       $(this).closest(".ui-dialog").find(".ui-button#prevB").removeClass("hidden");    
       $(this).closest(".ui-dialog").find(".ui-button#nextB").addClass("hidden");    
      } 
     }   
    }, 
    // http://api.jqueryui.com/dialog/#event-create 
    // Triggered when the dialog is created. 
    // Initialize the dialog with the create callback 
    create:function() { 
     $(this).closest(".ui-dialog").find(".ui-button#prevB").addClass("hidden"); 
    } 
}); 
Powiązane problemy