Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从iframe标记获取数据id值?_Javascript_Jquery_Iframe - Fatal编程技术网

Javascript 如何从iframe标记获取数据id值?

Javascript 如何从iframe标记获取数据id值?,javascript,jquery,iframe,Javascript,Jquery,Iframe,我在页面上有一个按钮。单击时,会打开一个iframe。iframe和button都有不同的原点。加载iframe时,我需要从它的标记中获取该iframe的数据id 我刚试过 window.onload = function() { var ifr=document.getElementById('iframe_test'); ifr.onload=function(){ this.style.display='block'; console.log(

我在页面上有一个按钮。单击时,会打开一个iframe。iframe和button都有不同的原点。加载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
作为输出。

通过使用Javascript,您可以使用
窗口执行以下操作。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>

样品
window.onload=函数(){
var iframes=parent.document.getElementsByTagName(“iframe”)[0];
警报(iframes.getAttribute(“数据id”))
}
要求:

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


你好,arora,我刚刚使用了,$(document).ready(函数(){var token=$(window.attr('data-id');警报(token);});但我仍然没有定义,你能告诉我哪里出了错吗?@Neela你能试试更新的代码片段并告诉我它是否适合你吗?我刚刚在iframe中加载了一个新页面,并为该页面包含了一个js文件。当我在js上使用你的解决方案时。我还没有定义。有人能帮我解决这个问题吗?我想你需要检查iframe页面,因为当我在本地计算机上测试时,我使用本地网页。它起作用了。您可以使用空白的本地页面进行测试。或者尝试注释行
/$(this.style.display='block'这可能会导致错误。
$(function() {
    $("#iframe_test").load(function(){
        $(this).style.display='block';
        console.log($("#iframe_test").data("id"));
    });
})
<body>
<iframe id='iframe_test' data-id='ddc' src='http://whatever.com'></iframe>
</body>
ddc