繁体   English   中英

是否可以使用 jquery: on 方法在文档中动态加载的 iframe 内容上触发事件

[英]Is it possible to trigger an event on dynamically loaded iframe contents in a document with jquery: on method

我想为 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不可用。 视图加载完成后,您可以注册事件侦听器。

$(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');
     });
   });
});

使用 JS First Get 元素获取点击事件的更好方法

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

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

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

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

暂无
暂无

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

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