Reputation: 13626
I have this 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 this row:
var d = $.parseJSON(element.data("ddd"));
I get the following error:
TypeError: element.data is not a function
Any idea why I get the above error?
Upvotes: 1
Views: 155
Reputation: 144709
In your code element
is a HTMLInputElement
object. It doesn't have .data()
method just like other HTMLElement
objects. If you want to use the jQuery .data()
method you should as first create a jQuery object:
$(element).data("ddd");
Also note that jQuery .data()
method tries the $.parseJSON
behind the scenes so there is no need to parse the datum, i.e. it returns the corresponding JavaScript structure:
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the 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 :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
If you use the .attr()
instead of the .data()
method then for parsing the JSON you have to use the $.parseJSON
or JSON.parse
method.
Upvotes: 1
Reputation: 36609
Try this:
function someevent(element)
{
var data=element.getAttribute("data-ddd");
var d=JSON.parse(data);
alert(d['a']);
}
Upvotes: 1
Reputation: 1365
I have made some modification in your code
Try this
<input type="button" id="someID" data-ddd='{"a": 1, "b": "2"}' />
$("#someID").click(function() {
var d = $(this).data("ddd");
alert(d.a);
});
Upvotes: 1