2012-05-28 20 views
9

我有一個jQuery模式,我想添加一個額外的按鈕,如果符合條件語句。有條件的按鈕添加到jQuery模式

最初的樣本代碼(切開):

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

所以當你看到上面有2個按鈕的模式,但我也想在那裏一些動態代碼添加到能夠滿足額外的按鈕,如果設置了一個變量。例如

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'); 

回答

16

你可以創建對話框之前創建buttons對象:

//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

或者,你可以創建你所需要的所有按鈕,然後顯示或隱藏取決於他們的情況,並根據您的對話框中會發生什麼。這樣做的一個方法是使用jqueryui對話框創建事件。

你可以參考一個工作示例在: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"); 
    } 
});