2013-12-24 47 views
1

是否有可能构建一个按钮数组并将其输入到一个变量中,我可以将它用于不同情况,并且每个按钮后面都有不同的代码?例如:不同的确认按钮数组jQuery UI

function showDialog(type, oEle, title, body) 
{ 
    $("#confirms").children(':first').html(body); 
    $("#confirms").attr('title', title).dialog({ 
     show: {effect: 'fadeIn', duration: 300}, 
     resizable: false, 
     modal: true, 
     buttons: { 
      "Yes": function() { 
       oEle.remove(); 
       $(this).dialog("close"); 
      }, 
      "No": function() { 
       $(this).dialog("close"); 
      } 
     } 
    }); 
} 

我想有针对不同的情况不同的按钮,所以我想调用ShowDialog的功能好几次,每次都使用不同的按钮使用此功能,与按钮不同的代码执行。

我该怎么做?

回答

1

您是不是要找像

function showDialog(title, body, buttons) { 
    $("#confirms").html(body).dialog({ 
     title: title, 
     buttons: buttons 
    }) 
} 

jQuery(function() { 
    $("#confirms").dialog({ 
     show: { 
      effect: 'fadeIn', 
      duration: 300 
     }, 
     resizable: false, 
     modal: true 
    }).dialog('close'); 

    $('#one').click(function() { 
     showDialog('remove one', 'some content', { 
      "Yes": function() { 
       $(this).dialog("close"); 
      }, 
      "No": function() { 
       $(this).dialog("close"); 
      } 
     }) 
    }) 

    $('#two').click(function() { 
     showDialog('remove two', 'some content 2', { 
      "Delete": function() { 
       $(this).dialog("close"); 
      }, 
      "Cancel": function() { 
       $(this).dialog("close"); 
      } 
     }) 
    }) 
}) 

演示:Fiddle

+0

这就是它!谢谢,圣诞快乐! –

0

那么在函数外部定义按钮对象怎么样?像:

var btns={ 
     "Option 1": function(){/*show dialog 1*/}, 
     "Option 2": function(){/*do something else*/}, 
     "Option 3": function(){/*show dialog 3*/}, 
     "Option 4": function(){/*do something else*/},   
    } 

function showDialog(type, oEle, title, body, btns) 
{ 
    $("#confirms").children(':first').html(body); 
    $("#confirms").attr('title', title).dialog({ 
     show: {effect: 'fadeIn', duration: 300}, 
     resizable: false, 
     modal: true, 
     buttons: btns 
    }); 
} 

编辑: - 以及对动态切换,可以在更高级别定义btns对象。然后通过的要显示在每个呼叫选项数组:

var showButtons=["Option 1","Option 4"]; 

function showDialog(type, oEle, title, body, showButtons){ 
    $.each(showButtons, function(i, j){ 
     if(btns[j]){ 
      btn[j] = btns[j]; 
     } 
    }); 

    //show dialog 
} 

$(this)而言,它会工作。对于oEle参数等其他内容,您可以用某种方式定义某些函数,以便将它传递给clouser(对句子抱歉)。如下:

btn['btnUsingoEle']=function(){ 
    oEle=...;//by the virtue of closure oEle will be available in 
      //dialog callbacks. 
} 
+0

但你如何限制对象按钮只在按钮中的每个单独的实例想?这就是我被困住的一点。 – Popnoodles

+0

每个函数中的代码如何?我应该使用'oEle'还是'$(this)'?当它在函数中运行时,它仍然可以正常执行,即使它是在函数之外定义的。这会产生错误吗? –