【问题标题】:Is it possible to trigger an event on dynamically loaded iframe contents in a document with jquery: on method是否可以使用 jquery: on 方法在文档中动态加载的 iframe 内容上触发事件
【发布时间】:2018-06-05 05:54:29
【问题描述】:

我想为 iframe 添加 mousemove 和 keypress 事件。以下代码适用于页面中现有的 iframe,但不适用于通过 javascript 在文档中动态创建的框架。

$('iframe').contents().keypress(function(){
         console.log('iframe keypress event fired1');
      });

      $('iframe').contents().mousemove(function(){
        console.log('iframe mousemove event fired2');
     });

我想在加载文档后对动态创建的框架进行这项工作。我在下面复制了整个代码。

<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Iframe Events Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
</head>
<body>
<div>Existing Iframe</div>
<input id="btnFrame" type="button" value="Load Dynamic Iframe"/>
<iframe width="200px" height="100px"></iframe>
</body>
<script>

$(document).ready(function() {
    console.log('document ready event...');
    $('#btnFrame').click(function(){
        console.log('btn click event...');
        console.log($('iframe#dynamic').length);
        if ($('iframe#dynamic').length === 0) {     
            prepareFrame();
        }       
    }); 
});

$(window).on('load', function() {
       $('iframe').on("load", function () {
         // All the contents of the iframe are loaded
         $('iframe').contents().keypress(function(){
            console.log('iframe keypress event fired');
         });
       });
    });


function prepareFrame() {
    var ifrm = document.createElement("iframe");
    ifrm.setAttribute("id", 'dynamic');
    ifrm.style.width = "640px";
    ifrm.style.height = "480px";
    document.body.appendChild(ifrm);
}

</script>

</html>

【问题讨论】:

  • 好的,您在 iframe 内的页面上有编辑权限吗?

标签: javascript jquery iframe jquery-on


【解决方案1】:

这是因为在您注册事件侦听器时您的 iframe 不可用。您可以在视图加载完成后注册事件监听器。

$(window).on('load', function() {
   $('iframe').on("load", function () {
     // All the contents of the iframe are loaded
     $('iframe').contents().keypress(function(){
        console.log('iframe keypress event fired');
     });
   });
});

【讨论】:

  • 这对我不起作用,我什至没有看到调试器甚至点击了 insde 块的 window->load。 ($window).on('load') 的任何其他替代方案?
  • 你使用的jquery版本是什么
  • jquery-3.1.1是版本
  • 我已经更新了答案,您是否尝试在您的$(window).on('load' 之后添加控制台日志以查看其是否有效?
  • $(window).on('load') 有效,但通过 java 脚本加载 iframe 时 $('iframe').on('load') 事件不起作用。跨度>
【解决方案2】:

使用 JS 获取点击事件的更好方法 首先获取iframe的元素

 const iframe = document.getElementsByTagName('iframe')[0];

然后在 HTML 中添加一个 ID 为 'play_video' 的 Anchor 标签并添加点击事件

const play = document.getElementById('play_video');
play.click();

这就是您在点击从 CMS 或数据库动态加载的 Iframe 时获得事件的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多