2012-05-28 18 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

また、あなたが必要とするすべてのボタンを作成し、ケースに依存し、あなたのダイアログで何が起こるかによって、それらを表示または非表示にすることができます。そのような方法の1つは、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"); 
    } 
}); 
:あなたがで作業例を参照することができます

関連する問題