【问题标题】:Why "opener.$(document).trigger('custom')" is not working?为什么“opener.$(document).trigger('custom')”不起作用?
【发布时间】:2012-12-12 09:10:29
【问题描述】:

我想用 jQuery 实现简单的发布/订阅模式。 所以我在父页面上添加了一些这样的代码:

父页面:

$(document).bind('custom', function() { ... });

当我像这样在同一页面上触发时,它工作正常:

同一页面:

$(document).trigger('custom');  // Working.

但是当我在弹出页面上触发它时,它不起作用。

弹出页面:

opener.$(document).trigger('custom');  // Not working.
$(opener.document).trigger('custom');  // Not working.

如果我将事件绑定到 <body> 元素,它可以找到。

父页面:

$('body').bind('custom', function() { ... });

弹出页面:

opener.$('body').trigger('custom');  // Working.

为什么绑定到document 对弹出窗口不起作用?

【问题讨论】:

  • 我认为因为如果您从父页面执行此操作,您将使用父页面中的 document 变量。如果你这样做 opener.$(opener.document).trigger('custom'); 会发生什么?

标签: javascript jquery publish-subscribe


【解决方案1】:

正如@11684 所说,让它发挥作用的答案是:

opener.$(opener.document).trigger('custom');

@Rory 的回答:

$(opener.document).trigger('custom');

无法正常工作,因为弹出窗口的 $ 没有 opener.document 的事件处理程序。

还有这个:

opener.$(document).trigger('custom');

不起作用,因为 document 是弹出窗口的 document,因此它与 opener.document 不同。

最后,

opener.$('body').trigger('custom');

因为开启者的$ 有事件处理程序并且参数(body)只是字符串(不是像document 这样的对象)。

【讨论】:

    【解决方案2】:

    您需要将整个opener.document 放入一个jQuery 对象中。在弹出窗口中试试这个:

    $(opener.document).trigger('custom'); 
    

    【讨论】:

    • 我已经尝试过了,但是没有用。 opener.$(opener.document).trigger 正在工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多