javascript 如何触发 iframe 事件 Jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10943727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:34:14  来源:igfitidea点击:

How to trigger an iframe event Jquery

javascriptjqueryiframe

提问by King Kong

I have an IFRAME and I want to trigger an event (which is inside the iframe) from the parent of an IFRAME:

我有一个 IFRAME,我想从 IFRAME 的父级触发一个事件(在 iframe 内):

Just a rough exampleof what I am trying to do :

只是我正在尝试做的一个粗略的例子

<iframe id="i">
  <div id="test"></div>
  <script>
  $(document).ready(function() {  // Event is binded inside the iframe 

   $("#test").live({ click : function() { alert("hello"); } });
  });
  </script>
</iframe>

<script>
$(document).ready(function() { // Want to trigger it from outside the iframe
 $("#i").contents().find("#test").trigger("click");
});
</script>

回答by

Your jquery is correct only problem is that that you are doing this when document is ready but at that time iframe is not getting fully loaded therefore div doesn't exist at that time and not triggers click. Change your main page script to

您的 jquery 是正确的,唯一的问题是您在文档准备就绪时执行此操作,但当时 iframe 未完全加载,因此当时不存在 div 并且不会触发单击。将您的主页脚本更改为

$(document).ready(function() {
    //want to trigger it from outside the iframe
    $("#i").load(function(){
        $("#i").contents().find("div").trigger("click");
    });
});

回答by Captain0

try this

试试这个

ger javascript event from within an iFrame

来自 iFrame 的 ger javascript 事件

but look at answer from Gilly

但看看 Gilly 的回答

document.myFrameName.myFunction(); 

regards

问候