javascript 使用javascript获取iframe中的元素

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

Get an element inside an iframe with javascript

javascriptgetelementframe

提问by ARAS

how to get Element From an Iframe? i want when the attribute of an element that its in a frame is true; it show a text, and else show another text; (sorry for bad english!)

如何从 iframe 中获取元素?我想当它在框架中的元素的属性为真时;它显示一个文本,否则显示另一个文本;(抱歉英语不好!)

like that:

像那样:

<!DOCTYPE html>
    <html>

    <head>
    <title>document</title>
    </head>

    <body>

    <iframe id="frame" src="">

    <!--we think in frame there is a span tag with button id-->
    <span id="button" aria-passed="true">sss</span>
    </iframe>
    <br>

    <!--if its true-->
    <p id="content1" style="display:none;">
    true
    </p>
    <!--if its false-->
    <p id="content2" style="display:none;">
    false
    </p>

    <!--now we want that, if aria-passed=true show content1 else content2.-->
    <script type="text/javascript">
    var Frame = document.getElementById('frame');
    if(new RegExp ("true","gim").test(frame.contentWindow.document.getElementById('button').aria-passed="true") == true) {
     document.getElementById('content1').style.display="block";
    }
    else {
     document.getElementById('content2').style.display="block";
     }
    </script>
    </body>

    </html>

now i want to say why this code does not work???? any ideas?

现在我想说为什么这段代码不起作用???有任何想法吗?

回答by not.your.ordinary.girl

It's much easier if you use jquery.

如果您使用 jquery,它会容易得多。

Example Code:

示例代码:

var elementattibutevalue = $("#frameID").contents().find("#htmlelementID").attr("SampleAttribute");

Hope it helps. (^_^)

希望能帮助到你。(^ _^)

回答by sarahm

I think the iframe in your code above is just a demonstration of how the loaded page code looks like? Take a look at this post Javascript - Get element from within an iFrame. Also change your 'Frame' variable to lowercase.

我认为上面代码中的 iframe 只是对加载的页面代码外观的演示?看看这篇文章Javascript - 从 iFrame 中获取元素。还将您的“框架”变量更改为小写。