使用jQuery在父窗口和子弹出窗口之间传递数据

15

我有以下的HTML代码

<tr>
    <td class="label" valign="top">
        Affiliate Party
    </td>
    <td class="field">
        <input type="hidden" name="ctl00$MainContent$ExternalAccountAttributes$AffiliatePartyId" id="AffiliatePartyId" />
        <input name="ctl00$MainContent$ExternalAccountAttributes$AffiliatePartyName" type="text" id="AffiliatePartyName" class="PartyLookup" />
    </td>
</tr>

还有下面的 Javascript/jQuery

$(".PartyLookup").after("<img src='Images/book_open.png' class='PartyLookupToggle' style='padding-left:4px;' />");

$(".PartyLookupToggle").click(function () {
    window.open("PartySearch.aspx", "PartySearch", "width=400,height=50");
    return false;
});

我需要能够标记任何带有class="PartyLookup"的PartyId输入字段,以便它修改DOM并在输入字段旁边包含图像。弹出窗口返回数据以填充隐藏和文本字段,但由于click()是通用的,我需要传递它输入字段的ID。我不知道如何做到这一点。有什么建议吗?


1
@micheel 即使在弹出窗口中,您也可以访问完整的 DOM。 - kobe
3个回答

25

父页面上的脚本:

$(".PartyLookupToggle").click(function () {
    var id = $(this).prev().prev().attr("id");
    var name = $(this).prev().attr("id");

    var url = "PartySearch.aspx?id=" + id + "&name=" + name;

    window.open(url, "PartySearch", "width=400,height=50");
    return false;
});

子页面上的脚本:

// Get the values from the URL using the jquery.query plug-in
var id = $.query.get("id");
var name = $.query.get("name");

// Get the values from the drop down
var newPartyId = $("#ddlMatchingParties").val();
var newPartyName = $("#ddlMatchingParties option:selected").text();

// Set them to the parent window
window.opener.$("#" + id).val(newPartyId);
window.opener.$("#" + name).val(newPartyName);

// Close the popup
window.close();

1
.prev() 是用来做什么的? - Jon
@Jon 获取匹配元素集合中每个元素的紧邻前一个同级元素:http://api.jquery.com/prev/ - mhenry
这是StackOverflow上最好的帖子之一,最好的之一!救命稻草! - Tastybrownies

6
在使用jQuery时,非常简单,在您的子窗口(弹出窗口)中调用父窗口对象即可:
$("#txtCodCliente", opener.window.document).val("VALUE TO "); //assign

$("#btnSelCliente", opener.window.document).click();

使用opener.window.document告诉jQuery该对象在打开弹出窗口的窗口中。


2
请看这篇教学文章:http://www.plus2net.com/javascript_tutorial/window-child3.php 基本上,你需要在子窗口的表单中执行此操作。你需要传递一个值,如下所示:
opener.document.f1.p_name.value="Any value";

其中f1是父窗口中表单的ID,p_name是表单中字段的名称。

一旦您在父窗口中获取了字段的值,您可以随意使用它。

编辑:

要将信息传递给子窗口,最简单的方法可能是通过查询字符串,然后从子窗口读取查询字符串。 在这种情况下,可能类似于:

$(".PartyLookupToggle").click(function () {
    window.open("PartySearch.aspx?id=" + $(this).prev().attr('id'), "PartySearch", "width=400,height=50");
    return false;
});

1
是的,我理解。然而,我需要传递与当前$(this)相关联的元素的ID到子窗口,以便在返回值时我知道表单元素的“p_name”。 - mhenry
好的,但是根据我在问题中发布的 HTML 结构,我需要找到一种方法让 jQuery 获取在可点击图像左侧的文本字段的 ID(由 jQuery 添加到 DOM 中)。 - mhenry
再次编辑。只需使用.prev()向后遍历文本字段,以获取其ID。 - Ender

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接