Why jQuery .data() function is not accessing HTML5 camel-case data attribute -


i have button in web page:

<button class="slidetoggle" data-slidetoggle="slider">slidetoggle</button> 

when button clicked trying access data stored inside data-slidetoggle attribute useing following code, nothing.

$('body').on('click', '.slidetoggle', function(){     alert($(this).data('slidetoggle')); }); 

but works when use:

alert($(this).attr('data-slidetoggle')); 

this problem occurs when use camel-case data attribute. new html5 , jquery , can not figure out going wrong it.

all previous answers miss 1 thing: can work existing html structure. consider this:

$('body').on('click', '.slidetoggle', function(){     alert($(this).data('slidetoggle')); // wait, what? }); 

to understand happens here, it's crucial check following lines in jquery source code:

name = "data-" + key.replace( rmultidash, "-$1" ).tolowercase(); data = elem.getattribute( name ); 

see, jquery here follows convention of dataset api, converting foobar property data-foo-bar name of element's attribute.

in case, converts 'slidetoggle' 'data-slide-toggle' - , there's no such attribute in html, apparently.

however, data('slidetoggle') works fine, getattribute default performs case-insensitive search among element's attributes. therefore, might wrote 1 as...

<button data-slidetoggle="l33t!"></button> 

... , still would have worked. )

still, i'd rather recommend following dataset api convention, breaking camelcased complexword data attributes hyphenated complex-word notation.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -