简体   繁体   English

使用自定义参数触发JavaScript事件并使用jQuery捕获它

[英]Fire JavaScript event with custom parameter and catch it with jQuery

I'm currently firing a custom JavaScript event like that from the page itself to the iframe document: 我目前正在从页面本身到iframe文档触发一个自定义JavaScript事件:

// Create iframe
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'URL to load');
document.body.appendChild(iframe);

// Event itself
var event = document.createEvent('HTMLEvents');
event.custom = 'example param';
event.initEvent('custom', false, true);
iframe.contentWindow.window.document.dispatchEvent(event);

Now on this iframe page I have jQuery available. 现在,在此iframe页面上,我可以使用jQuery。 How could I catch the event (which works) and also (important) get the custom (object) parameter? 如何捕捉事件(有效)并且也(重要)获取自定义(对象)参数?

Catching it like that: 像这样捕捉它:

$(document).on('custom', function(e, param) {
    alert(e); // [object Object] -> normal jQuery event data without any special data
    alert(e.custom); // undefined
    alert(param); // undefined
});

How could I get the custom parameter data without adding jQuery to the page itself which contains the iframe? 如何在不将jQuery添加到包含iframe的页面本身的情况下获取自定义参数数据?

jQuery wraps the original DOM event. jQuery包装了原始的DOM事件。 The original event should be available through the originalEvent property of the jQuery event. 原始事件应该可以通过jQuery事件的originalEvent属性获得。

e.originalEvent.custom

should evaluate to your custom value, in this case 'example param' . 应该评估为您的自定义值,在这种情况下为'example param'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM