2011-11-27 99 views
0

我正面临JavaScript对象的问题。我在页面上有一些文本,点击时应该转换为文本框。问题是,当我单击文本时,控制台显示错误消息JavaScript对象不能正常工作

“textNode未定义或为空且tn未定义”。

请帮助,我想以某种方式解决这个问题,以便我不必从头标移动JavaScript代码到任何其他位置。

这里是我的代码:

<!DOCTYPE HTML> 
<html> 
<head> 
<title>Span to Text Box - Demo - DOM</title> 
<script type="text/javascript" language="javascript"> 
function preload() 
{ 
if(!tn) var tn=new Object(); 
tn.variables= 
{ 
textboxNode: document.getElementById('textbox'), 
textNode: document.getElementById('text'), 
textValue: textNode.firstChild.nodeValue, 
doneButton: document.getElementById('done') 
}; 
} 

function change() 
{ 
tn.variables.textboxNode.setAttribute('value', textValue); 
tn.variables.textNode.style.display = 'none'; 
tn.variables.textboxNode.setAttribute('type','text'); 
tn.variables.doneButton.setAttribute('type','button'); 
} 
function changeBack() 
{ 
tn.variables.textNode.firstChild.nodeValue = textboxNode.value; 
tn.variables.textNode.style.display = 'block'; 
tn.variables.textboxNode.setAttribute('type', 'hidden'); 
tn.variables.doneButton.setAttribute('type','hidden'); 
} 
</script> 
</head> 

<body onload= "preload()"> 
<p id="text" onClick="change()">Click me!</p> 
<form onSubmit="return false;"> 
    <input type="hidden" id="textbox" /> 
    <input type="hidden" id="done" onClick="changeBack()" value="Done" /> 
</form> 

</body> 
</html> 

在此先感谢。

+0

范围之外的什么应每JAVA脚本程序员了解用户?我想在这里与我所有的Freinds分享这个最有用的帖子。这里是链接:http://stackoverflow.com/q/2628672/1067051 –

回答

1

对象tn位于preload函数的本地。

把它定义为全局变量,而不是:

var tn = new Object(); 
function preload() 
{ 
    tn.variables= 
    { 
     //.... 
    } 
} 

而且,你不能得到其他的属性值,当你刚刚定义的对象。

变化textValue是一个函数:

tn.variables = 
{ 
    textboxNode: document.getElementById('textbox'), 
    textNode: document.getElementById('text'), 
    textValue: function() { 
     return this.textNode.firstChild.nodeValue; 
    }, 
    doneButton: document.getElementById('done') 
}; 

然后调用它的功能以及,例如:

tn.variables.textboxNode.setAttribute('value', tn.variables.textValue()); 
+2

谢谢一吨,你的指导真的帮了我很多 –

1

我觉得你的TN变量未正确在全局范围内设置。尝试修改您的JavaScript的顶部是这样的:

<script type="text/javascript" language="javascript"> 
var tn = null; 
function preload() 
{ 
    if(!tn) 
    { 
     tn=new Object(); 
    } 
    tn.variables= 
    { 
    textboxNode: document.getElementById('textbox'), 
    textNode: document.getElementById('text'), 
    textValue: textNode.firstChild.nodeValue, 
    doneButton: document.getElementById('done') 
    }; 
} 
+2

非常感谢朋友 –

+1

没有问题 - 请考虑投票了有帮助的答案;-) ppl像我一直很高兴获得一些声誉 – Grrbrr404

+1

当然,为什么不:-) –

1

与开始,全局定义TN - 预紧

+1

感谢您的帮助 –

+0

没有probs ..与软件运气最好..你有没有尝试在Safari/Chrome开发人员工具的Javascript调试?或Firefox上的Firebug?有用的东西.. – Lloyd