私が作成した次の jquery プラグインを見てください。
(function($) {
//
// Constructor.
//
var Tb = function(element, options) {
var self = this;
this.options = options;
this.$element = $(element);
this.$input = $(element).find('.tb-input');
this.$label = $(element).find('.tb-label');
this.$element
.proxy('click', this.$input.click)
.proxy('val', this.$input.val);
};
Tb.prototype = {
constructor: Tb
};
//
// jQuery plugin.
//
$.fn.tb = function(option) {
return this.each(function() {
var $this = $(this)
, data = $this.data('tb')
, options = $.extend({}, $.fn.tb.defaults, $this.data(), typeof option == 'object' && option);
if (!data) {
$this.data('tb', (data = new Tb(this, options)));
}
if (typeof(option) == 'string') {
data[option]();
}
});
};
$.fn.tb.defaults = {};
$.fn.tb.Constructor = Tb;
})(window.jQuery);
HTML (デモ)
<div id="tb-user-name" class="tb">
<label class="tb-label">This is the placeholder</label>
<input type="text" class="tb-input" />
</div>
JavaScript初期化:
$('#tb-user-name').tb();
基本的に私がこれを行うと:
$('#tb-user-name').val(); // Should return the value of the input not the "container".
$('#tb-user-name').focus(); // Should focus on the input, not the "container"
しかし、コードが機能していません。どうすればよいですか? 「on」を試してみましたが、それも機能しません。少し回避するだけでフォーカスが機能しますが、「val」はイベントではなく関数です。
更新 (動作しますがハック)
http://jsfiddle.net/tppiotrowski/WSdmL/3/
このソリューションについて@teddybeardに感謝しますが、これはちょっとハックであるため、これは最善の方法ではありません.すべてのキーイベントでvalイベントがトリガーされるため、誰かが私を助けてくれるなら、私は代替手段を探しています.驚くばかり。