javascript 将事件监听器添加到 iFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30397732/
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-28 12:07:57  来源:igfitidea点击:

addEventListener to iFrame

javascriptjqueryeventsmouse

提问by Darko Martic

I'm tryin to add event listener to mouseup inside iframe object:

我正在尝试向 iframe 对象内的 mouseup 添加事件侦听器:

$("#myIFrame").contents().find("body").bind("mouseup", function() {
    //e.preventDefault(); //doesn't make difference
    alert('inside');
});

This doesn't work. Any ideas?

这不起作用。有任何想法吗?

回答by Muhammad Bilal

This will work:

这将起作用:

 $('#myIFrame').load(function(){
     //then set up some access points
     var contents = $(this).contents(); // contents of the iframe
     $(contents).find("body").on('mouseup', function(event) { 
         alert('test'); 
     });
 });

回答by Vince Pike

If you just want a plain vanilla Javascript way, you can use the following:

如果您只想要一个普通的 Javascript 方式,您可以使用以下内容:

var iframe = document.getElementById('myIFrame');
iframe.contentDocument.body.addEventListener('mouseup', Handler);

function Handler() {
    alert('works');
}

回答by wast

$($("#iframeid").contents()[0], window).find('body').bind("mouseup", function(e) {
    alert("works");
});

Try this. Works in jsfiddle. Enjoy.

试试这个。在 jsfiddle 中工作。享受。

回答by Maddy

Try this working on chrome, just tested

试试这个在 chrome 上工作,刚刚测试过

As per my knowledge, Iframe must be from same domain.

据我所知,Iframe 必须来自同一个域。

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title> - jsFiddle demo</title>
    <script type='text/javascript' src='//code.jquery.com/jquery-1.8.3.js'></script>

    <script type='text/javascript'>
        $(window).load(function () {            
            var $frame = $("#myIFrame");
            $frame.contents().bind("mouseup", function (e) {
                alert('inside');
            });
        });
    </script>
</head>
<body>
    <iframe id="myIFrame" src="/WebForm4.aspx" style="position:absolute; width:500px; height:500px;left:0px; top:50px"></iframe>
</body>
</html>