Skip to content

Instantly share code, notes, and snippets.

@Leko
Created February 13, 2014 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leko/8973807 to your computer and use it in GitHub Desktop.
Save Leko/8973807 to your computer and use it in GitHub Desktop.
// overwride $.data(key, value)
;(function(global, $) {
'use strict';
var originalData = $.fn.data;
$.fn.data = function(key, value) {
if(typeof value !== 'undefined') {
return $(this).attr('data-' + key, value);
} else {
return originalData.call(this, key);
}
};
}(this, this.jQuery));

jQuery.datasetter.js

概要

jQueryのdata(key, value)メソッドがHTMLのdata-*を書き換える挙動にしたかったので作成しました。
data(key)については、HTML5のdata-*を利用しているので、従来のAPIをそのまま利用する(上書きしない)つくりになっています。

demo

HTML

<p>
	data-hoge属性がなかった#hogeのdata-hogeは<strong id="hoge"></strong>です<br>
	data-foo属性があり、かつ上書きしていない#fooのdata-fooは<strong id="foo" data-foo="123456789"></strong>です<br>
	data-bar属性が有り、かつ上書きした#barのdata-barは<strong id="bar" data-bar="123456789"></strong>です
</p>
<script src="jquery.datasetter.js"></script>

js

;(function(global) {
    'use strict';

    $(function() {
        var $hoge = $("#hoge"),
            $foo = $("#foo"),
            $bar = $("#bar");

        // data set
        $hoge.data('hoge', 'HOGEHOGE');
        $bar.data('bar', 'BARBARBAR');

        // display
        $hoge.text($hoge.data('hoge'));
        $foo.text($foo.data('foo'));
        $bar.text($bar.data('bar'));
    });
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment