JavaScript对象不工作

JavaScript object not working

本文关键字:工作 对象 JavaScript      更新时间:2023-09-26

我正面临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>

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

我认为你的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')
   };
}

首先,全局定义tn -在preload

的作用域之外