デバッグにも便利!jQuery.tapの紹介
突然ですが
こういうコードのデバッグってどうしますか?
$('#aaa')
.find('.bbb')
.filter(':first')
.addClass('head')
.end()
.end()
.parents('tag')
.children(':first')
.addClass('head')
.end()
.end()
.end()
;
jQueryのmethod chainは書くのはいいけど、デバッグが面倒
なのでこういうコードを読み込む
$.fn.tap = function (func) {
$.isFunction(func)
? func.call(this, this)
: (window.console && window.console.debug(this))
;
return this;
};
で、こう書く
$('#aaa')
.find('.bbb').tap()
.filter(':first').tap()
.addClass('head')
.end()
.end()
.parents('tag').tap()
.children(':first').tap()
.addClass('head')
.end()
.end()
.end()
;
そうすると.tap()を書いた部分でconsole.debugに現在選択されているjQuery objectの一覧が出力される
functionを渡せば選択されてるjQuery objectを引数にfunctionを呼び出すのでそういう使い方も
何より7行!