I want to be able to basically set custom attributes on an HTML element (preferably using jQuery). i.e.
$("#element").attr('myVar','10px');
And this works perfectly in browsers such as Chrome and Firefox. However, apparently not even IE 8 supports custom attributes, unfortunat开发者_高级运维ely. How can I do something similar that is IE-compatible?
I've tried just attempting to set the value such as
obj.myValue = "10px";
But when I attempted to retrieve the value later in the script, it was undefined.
Don't set custom attributes directly on the element. Why? Because there are reserved properties and it's messy and buggy and conflicts will arise. Instead, use jQuery's .data
which internally stores custom properties/keys per DOM objects.
$('#element').data('key', 'value');
Get the value by just specifying $('#element').data('key')
.
Use jQuery data
method. apidocs here.
The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks
精彩评论