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()を実行するために 2 番目のケースを実行しなかったためです。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);
    };

編集

このフィドルの例を参照してください。

于 2012-06-14T13:33:50.093 に答える