Reputation: 404
How do I access values set by $.data() inside a function or object
$('#timers').data('firsttimer', 100);
//prints 100
document.write($('#timers').data('firsttimer'));
function blah(){
//Prints nothing
document.write($('#timers').data('firsttimer'));
}
blah();
See this jsfiddle for easy access to test the code http://jsfiddle.net/JUfd8/
Upvotes: 2
Views: 124
Reputation: 141869
The behavior is not consistent across all browsers. Remember, on jsfiddle this code is already wrapped inside the window load callback since you chose the onLoad
setting on the left. Once the DOM is loaded, any subsequent changes using document.write
will replace the entire document.
Here's the relevant text from the HTML5 specs on document.write:
Unless called from the body of a script element while the document is being parsed, or called on a script-created document, calling this method will clear the current page first, as if document.open() had been called.
Here's how the browsers are behaving on my Mac given this code:
<b>
and <i>
tags respectively.<div id="timers></div>
does not exist anymore in the new document.However, it does print "100" the first time you call document.write
on Opera and Firefox
document.write($('#timers').data('firsttimer'));
because the function argument $('#timers').data('firsttimer')
is evaluated first and since the original document is intact at this point, we get the value 100, which is then passed to document.write
, that then recreates the entire document. Therefore, all subsequent calls to fetch the data associated with #timers
returns undefined.
Upvotes: 1
Reputation: 322492
I'm having trouble with document.write()
inside the function call for some reason, but it works fine if I use jQuery's .append()
.
function blah(){
$('body').append($('#timers').data('firsttimer'));
};
EDIT:
Found this stackoverflow question regarding document.write
:
Why is document.write considered a "bad practice"?
An interesting sentence from one of the answers in that post:
As long as you don't try to use it after the document has loaded, document.write is not inherently evil, in my humble opinion.
So that may be the key to the trouble (or part of it, anyway).
Upvotes: 3
Reputation: 24340
In this case, I believe your document.write is stomping on the DOM in some strange way, wiping out your timers div. Switching both of the document.write calls to alert calls instead (and adding a line to invoke blah()) allowed me to see both alert boxes, both showing the value 100.
<div id="timers"></div>
js code:
$('#timers').data('firsttimer', 100);
//shows 100
alert($('#timers').data('firsttimer'));
function blah(){
//Prints nothing
alert($('#timers').data('firsttimer'));
}
blah();
Upvotes: 1