jQuery .data()

jQuery .data() gets or sets data attribute of the target element; jQuery .data() example;

js:


$(function(){

    $('.log span').text( $('.target').data('datakey') );

    

    $('.get-data').click(function() {

        var datakey = $('.target').data('datakey'); // get data attribute

        $('.log span').text( '[get] ' + datakey );

    });

    $('.set-data').click(function() {

        $('.target').data('datakey', 'abc'); // set data attribute = 'abc'

        var datakey = $('.target').data('datakey');

        $('.log span').text( '[set] ' + datakey );

    });

    $('.set-data2').click(function() {

        $('.target').data('datakey', '123'); // set data attribute = '123'

        var datakey = $('.target').data('datakey');

        $('.log span').text( '[set] ' + datakey );

    });

});​

html:


<div class="target well" data-datakey="default-val">.target element with data attribute</div>

<div class="form-actions btn-toolbar">

    <span class="btn get-data">get data attr</span>

    <span class="btn set-data">set data attr = 'abc'</span>

    <span class="btn set-data2">set data attr = '123'</span>

</div>

<div class="log">data value: <span class="label label-info"></span></div>​

Leave a Comment