0

我试图弄清楚为什么我不能像访问非嵌套函数时那样以类似的方式访问嵌套函数(也许有更好的方法来解释这一点。

换句话说,这有效:

<html>
<head>
<title>Working with elements</title>
</head>

<script type="text/javascript">
var my_div = null;
var newDiv = null;

function addElement()
{
  // create a new div element
  // and give it some content
  newDiv = document.createElement("div");
  newContent = document.createTextNode("Hi there and greetings!");
  newDiv.appendChild(newContent); //add the text node to the newly created div.

  // add the newly created element and it's content into the DOM
  my_div = document.getElementById("org_div1");
  document.body.insertBefore(newDiv, my_div);
}

</script>

<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>

这不起作用:

<html>
<head>
<title>Working with elements</title>
</head>

<script type="text/javascript">
var my_div = null;
var newDiv = null;

function addElement()
{
    this.getFieldset = function() {
        // create a new div element
        // and give it some content
        newDiv = document.createElement("div");
        newContent = document.createTextNode("Hi there and greetings!");
        newDiv.appendChild(newContent); //add the text node to the newly created div.

        // add the newly created element and it's content into the DOM
        my_div = document.getElementById("org_div1");
        document.body.insertBefore(newDiv, my_div);
    }
}

</script>

<body onload="addElement.getFieldSet()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>
4

1 回答 1

4

这是因为您从未addElement()在第二种情况下执行以执行this.getFieldset = ...分配。

您可以将代码更改为

function addElement() {}

addElement.getFieldSet = function() {
        // create a new div element
        // and give it some content
        newDiv = document.createElement("div");
        newContent = document.createTextNode("Hi there and greetings!");
        newDiv.appendChild(newContent); //add the text node to the newly created div.

        // add the newly created element and it's content into the DOM
        my_div = document.getElementById("org_div1");
        document.body.insertBefore(newDiv, my_div);
    };

编辑

请参阅this fiddle的示例。

于 2012-06-14T13:33:50.093 回答