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

San*_*dra 7 iframe jquery 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>

...
Run Code Online (Sandbox Code Playgroud)

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

<form id="(dinamic_id)" >
    <input class="(class_input)" />
</form>
Run Code Online (Sandbox Code Playgroud)

我的jquery函数:

$(".class_input").change(function() {
    $(this).closest("form").submit();
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

要么

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

返回null而不是"Some some here here".

Gor*_*ram 2

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

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

我进行了快速测试,一切正常。

编辑:解释

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

alert($(parent_div + " .element_1").html());
//     ( [object]  +    [string]  )
Run Code Online (Sandbox Code Playgroud)