有一个按钮(实际上很多),它有一个事件处理程序:
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');
}
}
处理程序会更改按钮的状态。
在第一次点击当前按钮之前记住文本节点的标准方式(模式)是什么,并在第二次点击时返回它(在同一个按钮上)?
你能记住javascript变量中的文本节点,而不是用于存储信息HTML元素吗?
不使用全局变量。
答案 0 :(得分:1)
您可以在元素本身上创建属性,例如:
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');
}
}
答案 1 :(得分:1)
你可以使用一个函数吗?
<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>