JavaScript对象无效

时间:2011-11-27 09:03:26

标签: javascript javascript-objects

我遇到了JavaScript对象的问题。我在页面上有一些文本,单击时应转换为文本字段。问题是,当我单击文本时,控制台会显示错误消息

  

“textNode未定义或null且tn未定义”。

请帮忙,我想以某种方式解决这个问题,这样我就不必将JavaScript代码移到head标签的任何其他位置。

这是我的代码:

<!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>

提前致谢。

3 个答案:

答案 0 :(得分:1)

对象tnpreload函数的本地对象。

将其定义为全局变量:

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());

答案 1 :(得分: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)

首先,全局定义tn - 超出预加载范围