从iframe访问父窗口的元素(jquery)

时间:2012-02-05 12:28:56

标签: jquery iframe jquery-selectors

我有几个dinamically创建的div,里面有相同的元素:

<div id="(dinamic_id_1)">
    <div class="(element_1)">Some text here</div>
    <input class="(element_2)" />
    <iframe class="(element_3)" src="form.php?id=(dinamic_id_1)" />
</div>

<div id="(dinamic_id_2)">
    <div class="(element_1)">Some text here</div>
    <input class="(element_2)" />
    <iframe class="(element_3)" src="form.php?id=(dinamic_id_2)" />
</div>

...

iframe中有一个表格看起来像这样:

<form id="(dinamic_id)" >
    <input class="(class_input)" />
</form>

我的jquery函数:

$(".class_input").change(function() {
    $(this).closest("form").submit();
});

我希望在父窗口上提交的其他操作,在div中包含的与表单共享相同ID的元素上执行。我必须得到父div中的html:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert($(parent_div).html());

但我无法找到div中的元素,例如:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert($(parent_div+" .element_1").html());

var parent_div = $("div#"+$(this).closest("form").attr("id")+" .element_1", parent.document);
alert($(parent_div).html());

返回null而不是“Some some here here”。

1 个答案:

答案 0 :(得分:2)

尝试将代码修改为以下内容:

var parent_div = $("div#"+$(this).closest("form").attr("id"), parent.document);
alert(parent_div.children('.element_1').text());

我敲了一个快速测试结束,一切正常。

编辑:说明

问题是你试图将parent_div作为字符串引用,实际上它本身就是一个jQuery对象。

alert($(parent_div + " .element_1").html());
//     ( [object]  +    [string]  )
相关问题