There is a button (actually a lot of them), it has an event handler:
el.onclick = function(){
if(this.className.indexOf("minimized") != -1){
this.firstChild.nodeValue = 'turn back';
this.className = this.className.replace("minimized", 'expanded');
}
else if(this.className.indexOf("expanded") != -1){
this.firstChild.nodeValue = 'what was there before the first click'开发者_开发百科;
this.className = this.className.replace("expanded", 'minimized');
}
}
Handler changes the state of the button.
What is the standard way (pattern) to memorize a text node before the first click on current button and return it on the second click (on the same button)?
Can you remember text node in a javascript variable, and not used for storing information HTML elements?
Without the use of global variables.
You can create a property on the element itself, for example:
el.onclick = function(){
if(this.className.indexOf("minimized") != -1){
this.originalText = this.firstChild.nodeValue; //store original
this.firstChild.nodeValue = 'turn back'; //change it
this.className = this.className.replace("minimized", 'expanded');
}
else if(this.className.indexOf("expanded") != -1){
this.firstChild.nodeValue = this.originalText; //restore it
this.className = this.className.replace("expanded", 'minimized');
}
}
You could use a function ?
<div id="test" class='minimized'>what was there before the first click</div>
<script type="text/javascript">
function f(el) {
var val = el.firstChild.nodeValue;
return function() {
if(this.className.indexOf("minimized") != -1){
this.firstChild.nodeValue = 'turn back';
this.className = this.className.replace("minimized", 'expanded');
}
else if(this.className.indexOf("expanded") != -1){
this.firstChild.nodeValue = val;
this.className = this.className.replace("expanded", 'minimized');
}
}
}
window.onload=function() {
var el = document.getElementById('test');
el.onclick = f(el);
}
</script>
精彩评论