javascript - Why do I get an error when I try to get HTML data from an attribute value? -


i have html code:

<input type = "button" id = "someid" data-ddd='{"a": 1, "b": "2"}' onclick = "someevent(this)" /> 

event implementation:

function someevent(element) {     var d = $.parsejson(element.data("ddd"));     alert(d.a); } 

on row:

 var d = $.parsejson(element.data("ddd")); 

i following error:

typeerror: element.data not function

any idea why above error?

in code element htmlinputelement object. doesn't have .data() method other htmlelement objects. if want use jquery .data() method should first create jquery object:

$(element).data("ddd"); 

also note jquery .data() method tries $.parsejson behind scenes there no need parse datum, i.e. returns corresponding javascript structure:

function dataattr( elem, key, data ) {     var name;      // if nothing found internally, try fetch     // data html5 data-* attribute     if ( data === undefined && elem.nodetype === 1 ) {         name = "data-" + key.replace( rmultidash, "-$&" ).tolowercase();         data = elem.getattribute( name );          if ( typeof data === "string" ) {             try {                 data = data === "true" ? true :                     data === "false" ? false :                     data === "null" ? null :                     // convert number if doesn't change string                     +data + "" === data ? +data :                     rbrace.test( data ) ? jquery.parsejson( data ) :                     data;             } catch ( e ) {}              // make sure set data isn't changed later             datauser.set( elem, key, data );         } else {             data = undefined;         }     }     return data; } 

if use .attr() instead of .data() method parsing json have use $.parsejson or json.parse method.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -