jqueryの小技
object 系
objectのkeyの長さをチェックする
test = {aaa: 10, bbb: 20}
Object.keys(test).length
これでとりあえず、チェックできる
objectのキーを削除
test = {aaa: 10}
delete test['aaa']
ajax
ajaxで処理する'#'のLinkで、Topページに飛んでしまうのを防ぐ
e.preventDefault()
を入れて解決
https://stackoverflow.com/questions/3252730/how-to-prevent-a-click-on-a-link-from-jumping-to-top-of-page-in-jquery
ajax の処理
$.ajax
#(送信するOptions)
.done (data) ->
#(成功したときの処理)
.fail (data) ->
#(失敗したときの処理)
.complete (data) ->
#(成功しても失敗しても必ず行う処理)
data系
dataを消すときは、removeData()
$(element).data('id', 'test-id') #dataを格納
$(element).removeData('id')
dataの中でBooleanをTrue/Falseを切り替える
$('#element').data('checked', !$('#element').data('checked'))
$('.test-button')if $('test-button').data('clickable')
とかくとだめ。→ data: { clickable: 'true' }
と直す。変数の場合は、bool_var.to_s
でオッケー。
jqueryでボタンにイベントをつけたが、buttonの中のiconをクリックしたときにうまくいかない
$(e.currentTarget)
を使うことで解決
button
buttonをdisable/enableする
$(button).prop 'disabled', true
$(button).prop 'disabled', false
bootstrap
bootstrap3でdropdownのsubmenuが削除された(https://github.com/twbs/bootstrap/pull/6342)
HTML
tabindexとは
tabindex=-1
とは、removes the element from the default navigation flow.
selectを解除する
$("option:selected").prop("selected", false)
or
$("option:selected").removeAttr("selected");
Event系
inputでエンターした時にtriggerする
$(element).on 'keypress', (e) ->
if e.which == 13
doSomething()
クリックするたびにClassをつけたり外したりする
$('.btn-class').on 'click', (e) =>
$(e.currentTarget).toggleClass('glyphicon-unchecked')
$(e.currentTarget).find('span').toggleClass('glyphicon-check')
$(e.currentTarget)
: to get a handle to the element that would have been this
. this is not same as $(e.target)
. $(e.targert)
はクリックされたものになるので、ButtonだったりIconだったりしてしまう。しかし、$(this)
は常に button
を示す。(問題は、fat arrowの中での$(this)
だったが…)
Use event.currentTarget which is always the object listening for the event; event.target is the actual target that received the event
inputに入力されたときにEventを発生させる
.on
のあとに 'change keyup paste'をつければよい
$('#filter-input').on 'change keyup paste', -> someFunc()
その他
embeded rubyのhaml(html)内でdataにBooleanを渡すときは、stringにする。
%button.test-button{ data: { clickable: true }, disabled: true }