0

我正在通过包含 JS 对象的 ajax 加载一个 html 页面。如何将新加载的(子)页面内的对象引用到父页面?

家长:

//parent.html

<script>

    function ParentObject() {
        this.children = new Array();
    }

    var aParentObject = new ParentObject();

    $.get('/url/to/child.html', function(data) {
        $("#child-div").html(data);
    });

</script>

孩子:

//child.html

<div>Some html element</div>

...

<script>
    function ChildObject() {
        this.someProperty = "I'm a Child";
    }

    var aChildObject = new ChildObject();
</script>
4

2 回答 2

2

You should use var when you declare new variable

var aChildObject = new ChildObject();

When you append a html containing a jscript the script will execute and you will get reference after that point. So you must ensure that you access the child variable after you insert it.

$.get('/url/to/child.html', function(data) {
    $("#child-div").html(data);
    //Access your child here
    alert(aParentObject.someProperty);
});
于 2012-05-25T09:04:45.903 回答
0

您可能想使用.load(). .get()您可以为“子”页面指定一个选择器,以.load()拉回您要检索的特定部分。

假设 child.htmldivid="child-div"

//parent.html

<script>

    function ParentObject() {
        this.children = new Array();
    }

    aParentObject = new ParentObject();

    $("#child-div").load('/url/to/child.html #child-div');

</script>

请参阅此处的“加载页面片段”部分:http: //api.jquery.com/load/

于 2012-05-25T09:11:22.617 回答