繁体   English   中英

如何从iframe广告代码获取data-id值?

[英]How to get the data-id value from iframe tag?

我在页面上有一个按钮。 单击时,将打开一个iframe。 iframe和按钮都有不同的来源。 加载iframe时,我需要从其代码中获取该iframe的数据ID。

我刚试过

window.onload = function() {

  var ifr=document.getElementById('iframe_test');
    ifr.onload=function(){
        this.style.display='block';
        console.log($("#iframe_test").data("id"));
    };
}

它只是返回: undefined为输出。

要求:

<script src="http://code.jquery.com/jquery-2.2.4.min.js"></script>

Javascript:

$(function() {
    $("#iframe_test").load(function(){
        $(this).style.display='block';
        console.log($("#iframe_test").data("id"));
    });
})

HTML:

<body>
<iframe id='iframe_test' data-id='ddc' src='http://whatever.com'></iframe>
</body>

Chrome控制台结果:

ddc

通过使用Javascript,可以使用window.onload执行以下操作:

var iframes= parent.document.getElementsByTagName("iframe")[0];
console.log(iframes.getAttribute("data-id"))

以下是一个演示:

<html>
    <head>
        <title>sample</title>
        <script type="text/javascript">
            window.onload = function() {

                var iframes= parent.document.getElementsByTagName("iframe")[0];
                alert(iframes.getAttribute("data-id"))
            }
        </script>
    </head>
    <body>
        <iframe id='iframe_test' data-id='foo' src='http://example.com'></iframe>
    </body>
</html>

暂无
暂无

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

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