LoginSignup
12
10

More than 5 years have passed since last update.

jquery1.11から.data()の挙動が変わっている件

Posted at

違い

<div id="hoge" data-hogehoge="foobar" />

jquery1.11未満

console.log('存在するid、存在するdata属性');
console.log($('#hoge').data('hogehoge')); // "foobar"

console.log('存在するid、存在しないdata属性'); //undefined
console.log($('#hoge').data('hoge'));

console.log('存在しないid');
console.log($('#hogehoge').data('hogehoge')); //null

jquery1.11以降

console.log('存在するid、存在するdata属性');
console.log($('#hoge').data('hogehoge')); // "foobar"

console.log('存在するid、存在しないdata属性'); //undefined
console.log($('#hoge').data('hoge'));

console.log('存在しないid');
console.log($('#hogehoge').data('hogehoge')); //undefined

これにより発生する問題

$.ajax()使用時

  • 送信するパラメータはajaxSetup()の中でajaxExtend()されて実際のパラメータとして使用される。
  • ajaxExtend中でundefinedのパラメータは無視される
  • 1.11未満はnullだったので、無視されずパラメータ的には空文字として送信されるが、1.11以降はundefinedなので、無視されてしまいパラメータとして送信されない。

その結果

  • param = {selected_value: $(xxx :selected).data(yyy)};みたいなコードが書かれていたので、項目が選択されていない時に値が飛んでこず、バリデート処理が入っていなかったのでエラーで落ちた。
  • どう見てもサーバー側処理のせいによるバグです、本当にありがとうございました。

おまけ

どうやら1.8.3の頃は存在しない要素に対して.data()した場合にはundefinedが返ってきていたのに、1.9になってnullを返すようになり、1.10でもそのままで、1.11で再びundefinedに戻ったようですね。

12
10
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
12
10