2010-05-06 131 views
12

創建具有類似按鈕的對話框時:jQuery UI的對話框按鈕

buttons: { 
      'button text': function(){        
       // do something 
      }, 

做我的Click事件處理程序中訪問按鈕?

$(this) 

是整個對話框的上下文/ jQuery對象。

我懷疑我必須是這樣的創意爲

$(this).find('button').attr(...) 

爲禁用按鈕嗎?

回答

18

的文檔dialog()說:

屬性鍵是 按鈕的文本。該值爲回撥 功能,當按鈕爲 時點擊。回調 的上下文是對話框元素; 如果您需要 訪問按鈕,則可用 作爲事件對象的目標

$('#myDialog').dialog({ 
    'title': 'My Dialog Header', 
    'buttons': { 
     'My Button': function(event) { 
      // here is the modification of the button 
      // opacity set to 25%, all events unbound 
      $(event.target).css({opacity: 0.25}).unbind(); 
     } 
    } 
}); 
8

對話框中的按鈕的格式爲<button><span>裏面,像這樣:

<button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"> 
    <span class="ui-button-text">Button text</span> 
</button> 

所以,當你點擊,實際click事件發生在該<span><button>,這取決於你的造型(上跨度例如保證金),所以得到<button>只是讓你的處理器上的按鈕,即使你已經在上面,像這樣:

buttons: { 
    'button text': function(e){ 
    $(e.target).closest("button") //this is the button, do something with it :) 
    } 
} 

Here's a quick demo of this working