jQueryのTips集
jQueryでよく使うTipsをまとめてみました。 (2015/01/23)

each
$.each [1, 2, 3], ->
console.log(@)
selectボックス
$('.select').val()
$('.select option:selected').text()
イベントハンドラ設定
$('.btn').click (event) ->
console.log("#{$(@).val()} is clicked')
console.log("#{event.target.val()} is clicked')
$(window).on 'click', '.btn', ->
console.log("#{$(@).val()} is clicked')
console.log("#{event.target.val()} is clicked')
イベントハンドラ確認
http://takuya-1st.hatenablog.jp/entry/2014/04/05/042658
jQuery._data($(window).get(0)).events
$(window).unbind('unload')
jQuery v1.8以降はunloadはdeprecated
Chromeではunloadは動作しません
http://www.jquerystudy.info/reference/events/unload.html
popstateイベント
仕様としては同一ドキュメントでの遷移の場合のみ発火します。
ただし、Chromeでは戻る/進むでも発火します。
Safariではさらに初期ページロード時にも発火します。
セレクタ利用例
$('a:not(.page-top, .about)')
$('[data-no-turbolink]')
$('img').parents('[data-no-turbolink]')
$('img').closest('a') #直近の親
オブジェクトの存在確認
if $('.content')[0]
console.log('exists')
Ajaxレスポンスをスクリプトとして実行
$.ajax url, dataType: 'script'
JSONを取得
$.ajax '/get_json/',
data: {'id': 1},
format: 'json',
success: (data) ->
console.log(data)
Mapしてjoinする
$('a').map((_, elem) -> $(elem).attr('href')).get().join(',')
配列操作
array = $([])
array.push(1)
array.each ->
console.log(@.valueOf())
$.inArray(1, array)
$.merge(array, [2, 3])