您可以制作自己的组件并从 textarea 扩展。此外,您在回调函数中做了 3 次相同的事情。并且您的 textarea 的 id 应该是唯一的。
这是您的组件的示例:
Ext.define('MyApp.ux.form.field.TextArea', {
alias: 'widget.textareacounter',
extend: 'Ext.form.field.TextArea',
labelAlign: 'top',
enableKeyEvents: true,
enforceMaxLength: false,
maxLength: 1000,
constructor: function(config) {
var me = this;
Ext.apply(me, config);
me.afterLabelTextTpl = ['<span style="margin-left:5px;">(' + me.maxLength + ' char. left)</span>'];
me.callParent()
},
initComponent: function () {
var me = this;
me.on({
keydown: me.calculateCharsLeft,
keyup: me.calculateCharsLeft,
afterrender: me.calculateCharsLeft,
scope: me
});
me.callParent();
},
calculateCharsLeft: function (textfield, e) {
var me = this;
var span = Ext.dom.Query.select('span', me.getEl().dom)[0];
var remaining = me.maxLength - me.getValue().length;
span.innerHTML = '(' + remaining + ' char. left)';
}
});
还有一个工作小提琴:http: //jsfiddle.net/johanhaest/cpLvK/2/