5

I use "data" attribute and in IE7 and I don't know how to get value of it. Can jQuery possibly help me?

I have this

window.event.srcElement.getAttribute('data-pk')

Of course it does not work.

Edit:

for (i=0; i < max; i++) {

    if (typeof attachEvent == 'undefined'){         
        //open[i].addEventListener('click', function(e){ openSlide(e.currentTarget.getAttribute('data-pk')), false});
        open[i].onclick = function(e){ openSlide(e.currentTarget.getAttribute('data-pk')), false};
    } else {
        open[i].attachEvent('onclick', function(){
            openSlide(window.event.srcElement.getAttribute('data-pk'))}, false);
    };
};

html

<div>                             
    <img class='image' data-pk='18' src='/site_media/media/img/120x180.jpg'>                             
    <img class='image' data-pk='13' src='/site_media/media/img/007b-300x224.jpg'>                             
    <img class='image' data-pk='15' src='/site_media/media/img/IMG_0549_1.jpg'>                             
</div> 
I159
  • 29,741
  • 31
  • 97
  • 132

4 Answers4

12

jQuery can help ... the data attribute works with the data() function in jQuery.

$(srcElement).data('pk');

You can use it with any data attribute, for example, if you had:

<div id="DivId" data-something="foo" data-somethingElse="bar">

You can get the data out by:

$('#DivId').data('something');
$('#DivId').data('somethingElse');

To set data:

$('#DivId').data('something', 'foo');
$('#DivId').data('somethingElse', 'bar');

Here is a link to jQuery .data()

EDIT:

I think you want:

$('.image').click(function () {
    openSlide($(this).data('pk'), false);
});
Martin
  • 11,031
  • 8
  • 50
  • 77
  • I did in this way: `open[i].attachEvent('onclick', function(){ openSlide($(this.srcElement).data('pk'))}, false);` And this is undefined. HTML is ok, data-pk exists. Can't get what I did wrong. – I159 Sep 09 '11 at 14:12
  • 1
    In the sample, should it be `$('#DivId').data('something');` ? – James Holwell Jul 04 '12 at 09:50
  • Sorry all ... fixed the missing quotes around the data element names – Martin Jun 04 '13 at 12:51
1

The top answer is outdated. Given the example <div id="DivId" data-somethingElse="bar"></div>, you will have to do $('#DivId').data('somethingelse') to get the data. The better standard way is to use snake case in HTML, which will yield camelcase in JavaScript:

HTML:

<div id="foo" data-something-else="bar"></div>

JS:

alert($('#foo').data('somethingElse')); // Alerts "bar"
Ezekiel Victor
  • 3,877
  • 1
  • 27
  • 28
0

In jQuery you can use the data method, like this:

$(srcElement).data('pk');

Note that the string to pass into data is just 'pk', you simply drop the 'data-' part of the attribute.

nikmd23
  • 9,095
  • 4
  • 42
  • 57
0

You can use jQuerys (or other libs) attr getter. Or you can look into jQuery source and find out how they achieved cross-browser consistency.

Adam Jurczyk
  • 2,153
  • 12
  • 16