Recently I faced an issue regarding Global variables in Javascript.
I had to save a lot of data regarding many DOMElements and do manipulation later on them.
I had declared about 10 global variables. Getting them was fast but remembering which is related to which DOMElement was difficult.
So had to name them with ID's of the DOMElements prefixed to variables names. But I searched for an elegant method to do this job and yes I found that. jQuery again came to rescue here.
There is a method name .data which can be used to save values related to an DOMElement in form of a key-value pair. Can read the documentation of the method on the this link... jQuerydata I am going to give you a small implementation which explains how this works.
Sample HTML
<span class="yes" id="save">Click to Save Value</span>jQuery Scripts
<span class="no" id="get">Get Value</span>
$(".yes").click(function() {
var v = $("#save");
$.data(v, "key", "value!!!");
alert($.data(document.body, "bodyKey"));
});
$(".no").click(function() {
var v = $("#save");
if($.data(v, "key") != null ) {
alert($.data(v, "key"));
}
});
$(function (){
$.data(document.body, "bodyKey", "Global Body Variable");
});
I have also saved some value in document body, giving a way to declare global variables. Hope this helps..
PS: The code in this post won't work. You can save the scripts and html to try it out.
No comments:
Post a Comment