我想用 jQuery 实现简单的发布/订阅模式。 所以我在父页面上添加了一些这样的代码:
父页面:
$(document).bind('custom', function() { ... });
当我像这样在同一页面上触发时它工作正常:
同一页:
$(document).trigger('custom'); // Working.
但是当我在弹出页面上触发它时,它不起作用。
弹出页面:
opener.$(document).trigger('custom'); // Not working.
$(opener.document).trigger('custom'); // Not working.
如果我将事件绑定(bind)到 <body>
元素,它可以找到。
父页面:
$('body').bind('custom', function() { ... });
弹出页面:
opener.$('body').trigger('custom'); // Working.
为什么要绑定(bind)到 document
不在 Popup 上工作?
最佳答案
正如@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');
之所以有效,是因为 opener 的 $
具有事件处理程序,并且参数 (body
) 只是字符串(不是像 document
这样的对象)。
关于javascript - 为什么 "opener.$(document).trigger(' 自定义 ')"不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13836309/