2012-02-09 39 views
2

我想知道如何將onClick()方法添加到Ext.form.Text組件。如何將onClick方法添加到TextField(ExtJS框架)?

如果組件是一個按鈕,那麼我需要做的就是添加這一行:如果該組件是一個文本框

handler: function() {alert("Hello!");} 

但該行doesn't工作。看看下面的例子:

Ext.create('Ext.form.Panel', { 
    title: 'Contact Info', 
    width: 300, 
    bodyPadding: 10, 
    renderTo: Ext.getBody(), 
    items: [{ 
     id: 'myButton', 
     xtype: 'textfield', 
     name: 'name', 
     fieldLabel: 'Name', 
     style: 'background-color: #ddd;', 
     allowBlank: false, 
     handler: function() {Ext.getCmp('myButton').setValue("TEXT")} // Does not work! 
    }, { 
     xtype: 'button', 
     name: 'email', 
     fieldLabel: 'Email Address', 
     style: 'background-color: green', 
     textfieldStyle: 'background-color: green', 
     handler: function() {Ext.getCmp('myButton').setValue("TEXT")} // Works! 

    }] 
}); 
+0

這可能有助於[http://stackoverflow.com/questions/ 7260134/extjs-4-event-handling-tutorial/7261836#7261836](http://stackoverflow.com/questions/7260134/extjs-4-event-handling-tutorial/7261836#7261836) – 2012-02-09 07:38:19

回答

9

Handler是默認動作偵聽器的快捷方式。對於一個按鈕,這顯然是點擊,但文本字段沒有默認操作。此外,文本字段實際上並不觸發一個click事件,但你總是可以添加一個事件處理程序的DOM元素:

Ext.create('Ext.form.Panel', { 
    title: 'Contact Info', 
    width: 300, 
    bodyPadding: 10, 
    renderTo: Ext.getBody(), 
    items: [{ 
     id: 'myButton', 
     xtype: 'textfield', 
     name: 'name', 
     fieldLabel: 'Name', 
     style: 'background-color: #ddd;', 
     allowBlank: false, 
     listeners: { 
      render: function() { 
       this.getEl().on('mousedown', function(e, t, eOpts) { 
        Ext.getCmp('myButton').setValue("TEXT") 
       }); 
      } 
     } 
    }] 
}); 
+0

謝謝!是否有可能在按鈕聲明之外聲明偵聽器並使用on()方法調用它? – Rox 2012-02-09 09:25:28

+1

它是,但您必須檢查它是否呈現(您可以只在呈現的文本字段添加偵聽器)。或者,您可以擴展文本字段。以下是示例:http://jsfiddle.net/3ZZcZ/1/ – Krzysztof 2012-02-09 09:39:05

+0

即使點擊字段標籤,也會觸發此事件。如果你希望事件只在點擊實際字段時被觸發,那麼得到如下輸入元素:'var inputElement = this.getEl()。down('input')'並將'mousedown'事件綁定到該事件。小心不要使用'click'事件,因爲即使點擊字段標籤,它也可以在輸入上觸發。 – MarthyM 2016-10-13 10:11:32

2
Ext.create('Ext.form.Panel', { 
    title: 'Contact Info', 
    width: 300, 
    bodyPadding: 10, 
    renderTo: Ext.getBody(), 
    items: [{ 
     id: 'myButton', 
     xtype: 'textfield', 
     name: 'name', 
     fieldLabel: 'Name', 
     style: 'background-color: #ddd;', 
     allowBlank: false, 
     listeners: { 
      render: function(component) { 
       component.getEl().on('click', function(event, el) { 
        component.setValue("TEXT"); 
       }); 
      } 
     } 
    }, { 
     xtype: 'button', 
     name: 'email', 
     fieldLabel: 'Email Address', 
     style: 'background-color: green', 
     textfieldStyle: 'background-color: green', 
     handler: function() {Ext.getCmp('myButton').setValue("TEXT")} // Works! 

    }] 
});