LoginSignup
0
3

More than 5 years have passed since last update.

Railsでajaxを真面目に書いたときに調べたjs, jquery, coffeescript 関連をまとめておく(適宜更新予定)

Last updated at Posted at 2017-06-06

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 }

dropdownを複数btn-groupに入れるときは、2重にする

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3