2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQuery の data() と data- attributes

Posted at

say foo ボタンを押すと例外をアラートで表示、
say bar ボタンを押すとセットした関数が実行されます。

data-attributes.html
<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    </head>
    <body>
        <input type="button" id="button0" value="say foo" />
        <input type="button" id="button1" value="say bar" />
        <script type="text/javascript">
            var elm = document.querySelector('#button0');
            elm.dataset.foo = function () {
                alert('foo');
            };
            elm.addEventListener('click', function () {
                try {
                    elm.dataset.foo();
                } catch (e) {
                    alert(e.toString());
                }
            }, false);

            $('#button1').data('bar', function () {
                alert('bar');
            });
            $('#button1').click(function () {
                $(this).data('bar')();
            });

        </script>
    </body>
</html>
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?